PackageManagerService.java revision ad8a0da6a7b92e244953460068aebd4b40a5614e
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(mContext, 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        final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
9983                && SystemProperties.getInt("ro.vndk.version", 28) < 28;
9984        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
9985                && !pkg.isPrivileged()
9986                && (pkg.mSharedUserId != null)
9987                && !skipVendorPrivilegeScan) {
9988            SharedUserSetting sharedUserSetting = null;
9989            try {
9990                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9991            } catch (PackageManagerException ignore) {}
9992            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9993                // Exempt SharedUsers signed with the platform key.
9994                // TODO(b/72378145) Fix this exemption. Force signature apps
9995                // to whitelist their privileged permissions just like other
9996                // priv-apps.
9997                synchronized (mPackages) {
9998                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9999                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10000                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10001                        scanFlags |= SCAN_AS_PRIVILEGED;
10002                    }
10003                }
10004            }
10005        }
10006
10007        return scanFlags;
10008    }
10009
10010    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10011    // the results / removing app data needs to be moved up a level to the callers of this
10012    // method. Also, we need to solve the problem of potentially creating a new shared user
10013    // setting. That can probably be done later and patch things up after the fact.
10014    @GuardedBy("mInstallLock")
10015    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10016            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10017            @Nullable UserHandle user) throws PackageManagerException {
10018
10019        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10020        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10021        if (realPkgName != null) {
10022            ensurePackageRenamed(pkg, renamedPkgName);
10023        }
10024        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10025        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10026        final PackageSetting disabledPkgSetting =
10027                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10028
10029        if (mTransferedPackages.contains(pkg.packageName)) {
10030            Slog.w(TAG, "Package " + pkg.packageName
10031                    + " was transferred to another, but its .apk remains");
10032        }
10033
10034        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10035        synchronized (mPackages) {
10036            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10037            assertPackageIsValid(pkg, parseFlags, scanFlags);
10038
10039            SharedUserSetting sharedUserSetting = null;
10040            if (pkg.mSharedUserId != null) {
10041                // SIDE EFFECTS; may potentially allocate a new shared user
10042                sharedUserSetting = mSettings.getSharedUserLPw(
10043                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10044                if (DEBUG_PACKAGE_SCANNING) {
10045                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10046                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10047                                + " (uid=" + sharedUserSetting.userId + "):"
10048                                + " packages=" + sharedUserSetting.packages);
10049                }
10050            }
10051
10052            boolean scanSucceeded = false;
10053            try {
10054                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10055                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10056                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10057                        (pkg == mPlatformPackage), user);
10058                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10059                if (result.success) {
10060                    commitScanResultsLocked(request, result);
10061                }
10062                scanSucceeded = true;
10063            } finally {
10064                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10065                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10066                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10067                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10068                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10069                  }
10070            }
10071        }
10072        return pkg;
10073    }
10074
10075    /**
10076     * Commits the package scan and modifies system state.
10077     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10078     * of committing the package, leaving the system in an inconsistent state.
10079     * This needs to be fixed so, once we get to this point, no errors are
10080     * possible and the system is not left in an inconsistent state.
10081     */
10082    @GuardedBy("mPackages")
10083    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10084            throws PackageManagerException {
10085        final PackageParser.Package pkg = request.pkg;
10086        final PackageParser.Package oldPkg = request.oldPkg;
10087        final @ParseFlags int parseFlags = request.parseFlags;
10088        final @ScanFlags int scanFlags = request.scanFlags;
10089        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10090        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10091        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10092        final UserHandle user = request.user;
10093        final String realPkgName = request.realPkgName;
10094        final PackageSetting pkgSetting = result.pkgSetting;
10095        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10096        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10097
10098        if (newPkgSettingCreated) {
10099            if (originalPkgSetting != null) {
10100                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10101            }
10102            // THROWS: when we can't allocate a user id. add call to check if there's
10103            // enough space to ensure we won't throw; otherwise, don't modify state
10104            mSettings.addUserToSettingLPw(pkgSetting);
10105
10106            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10107                mTransferedPackages.add(originalPkgSetting.name);
10108            }
10109        }
10110        // TODO(toddke): Consider a method specifically for modifying the Package object
10111        // post scan; or, moving this stuff out of the Package object since it has nothing
10112        // to do with the package on disk.
10113        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10114        // for creating the application ID. If we did this earlier, we would be saving the
10115        // correct ID.
10116        pkg.applicationInfo.uid = pkgSetting.appId;
10117
10118        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10119
10120        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10121            mTransferedPackages.add(pkg.packageName);
10122        }
10123
10124        // THROWS: when requested libraries that can't be found. it only changes
10125        // the state of the passed in pkg object, so, move to the top of the method
10126        // and allow it to abort
10127        if ((scanFlags & SCAN_BOOTING) == 0
10128                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10129            // Check all shared libraries and map to their actual file path.
10130            // We only do this here for apps not on a system dir, because those
10131            // are the only ones that can fail an install due to this.  We
10132            // will take care of the system apps by updating all of their
10133            // library paths after the scan is done. Also during the initial
10134            // scan don't update any libs as we do this wholesale after all
10135            // apps are scanned to avoid dependency based scanning.
10136            updateSharedLibrariesLPr(pkg, null);
10137        }
10138
10139        // All versions of a static shared library are referenced with the same
10140        // package name. Internally, we use a synthetic package name to allow
10141        // multiple versions of the same shared library to be installed. So,
10142        // we need to generate the synthetic package name of the latest shared
10143        // library in order to compare signatures.
10144        PackageSetting signatureCheckPs = pkgSetting;
10145        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10146            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10147            if (libraryEntry != null) {
10148                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10149            }
10150        }
10151
10152        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10153        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10154            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10155                // We just determined the app is signed correctly, so bring
10156                // over the latest parsed certs.
10157                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10158            } else {
10159                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10160                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10161                            "Package " + pkg.packageName + " upgrade keys do not match the "
10162                                    + "previously installed version");
10163                } else {
10164                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10165                    String msg = "System package " + pkg.packageName
10166                            + " signature changed; retaining data.";
10167                    reportSettingsProblem(Log.WARN, msg);
10168                }
10169            }
10170        } else {
10171            try {
10172                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10173                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10174                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10175                        pkg.mSigningDetails, compareCompat, compareRecover);
10176                // The new KeySets will be re-added later in the scanning process.
10177                if (compatMatch) {
10178                    synchronized (mPackages) {
10179                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10180                    }
10181                }
10182                // We just determined the app is signed correctly, so bring
10183                // over the latest parsed certs.
10184                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10185
10186
10187                // if this is is a sharedUser, check to see if the new package is signed by a newer
10188                // signing certificate than the existing one, and if so, copy over the new details
10189                if (signatureCheckPs.sharedUser != null) {
10190                    if (pkg.mSigningDetails.hasAncestor(
10191                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10192                        signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10193                    }
10194                    if (signatureCheckPs.sharedUser.signaturesChanged == null) {
10195                        signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE;
10196                    }
10197                }
10198            } catch (PackageManagerException e) {
10199                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10200                    throw e;
10201                }
10202                // The signature has changed, but this package is in the system
10203                // image...  let's recover!
10204                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10205
10206                // If the system app is part of a shared user we allow that shared user to change
10207                // signatures as well as part of an OTA. We still need to verify that the signatures
10208                // are consistent within the shared user for a given boot, so only allow updating
10209                // the signatures on the first package scanned for the shared user (i.e. if the
10210                // signaturesChanged state hasn't been initialized yet in SharedUserSetting).
10211                if (signatureCheckPs.sharedUser != null) {
10212                    if (signatureCheckPs.sharedUser.signaturesChanged != null &&
10213                        compareSignatures(
10214                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10215                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10216                        throw new PackageManagerException(
10217                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10218                                "Signature mismatch for shared user: " + pkgSetting.sharedUser);
10219                    }
10220
10221                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10222                    signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE;
10223                }
10224                // File a report about this.
10225                String msg = "System package " + pkg.packageName
10226                        + " signature changed; retaining data.";
10227                reportSettingsProblem(Log.WARN, msg);
10228            } catch (IllegalArgumentException e) {
10229
10230                // should never happen: certs matched when checking, but not when comparing
10231                // old to new for sharedUser
10232                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10233                        "Signing certificates comparison made on incomparable signing details"
10234                        + " but somehow passed verifySignatures!");
10235            }
10236        }
10237
10238        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10239            // This package wants to adopt ownership of permissions from
10240            // another package.
10241            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10242                final String origName = pkg.mAdoptPermissions.get(i);
10243                final PackageSetting orig = mSettings.getPackageLPr(origName);
10244                if (orig != null) {
10245                    if (verifyPackageUpdateLPr(orig, pkg)) {
10246                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10247                                + pkg.packageName);
10248                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10249                    }
10250                }
10251            }
10252        }
10253
10254        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10255            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10256                final String codePathString = changedAbiCodePath.get(i);
10257                try {
10258                    mInstaller.rmdex(codePathString,
10259                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10260                } catch (InstallerException ignored) {
10261                }
10262            }
10263        }
10264
10265        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10266            if (oldPkgSetting != null) {
10267                synchronized (mPackages) {
10268                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10269                }
10270            }
10271        } else {
10272            final int userId = user == null ? 0 : user.getIdentifier();
10273            // Modify state for the given package setting
10274            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10275                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10276            if (pkgSetting.getInstantApp(userId)) {
10277                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10278            }
10279        }
10280    }
10281
10282    /**
10283     * Returns the "real" name of the package.
10284     * <p>This may differ from the package's actual name if the application has already
10285     * been installed under one of this package's original names.
10286     */
10287    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10288            @Nullable String renamedPkgName) {
10289        if (isPackageRenamed(pkg, renamedPkgName)) {
10290            return pkg.mRealPackage;
10291        }
10292        return null;
10293    }
10294
10295    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10296    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10297            @Nullable String renamedPkgName) {
10298        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10299    }
10300
10301    /**
10302     * Returns the original package setting.
10303     * <p>A package can migrate its name during an update. In this scenario, a package
10304     * designates a set of names that it considers as one of its original names.
10305     * <p>An original package must be signed identically and it must have the same
10306     * shared user [if any].
10307     */
10308    @GuardedBy("mPackages")
10309    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10310            @Nullable String renamedPkgName) {
10311        if (!isPackageRenamed(pkg, renamedPkgName)) {
10312            return null;
10313        }
10314        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10315            final PackageSetting originalPs =
10316                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10317            if (originalPs != null) {
10318                // the package is already installed under its original name...
10319                // but, should we use it?
10320                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10321                    // the new package is incompatible with the original
10322                    continue;
10323                } else if (originalPs.sharedUser != null) {
10324                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10325                        // the shared user id is incompatible with the original
10326                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10327                                + " to " + pkg.packageName + ": old uid "
10328                                + originalPs.sharedUser.name
10329                                + " differs from " + pkg.mSharedUserId);
10330                        continue;
10331                    }
10332                    // TODO: Add case when shared user id is added [b/28144775]
10333                } else {
10334                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10335                            + pkg.packageName + " to old name " + originalPs.name);
10336                }
10337                return originalPs;
10338            }
10339        }
10340        return null;
10341    }
10342
10343    /**
10344     * Renames the package if it was installed under a different name.
10345     * <p>When we've already installed the package under an original name, update
10346     * the new package so we can continue to have the old name.
10347     */
10348    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10349            @NonNull String renamedPackageName) {
10350        if (pkg.mOriginalPackages == null
10351                || !pkg.mOriginalPackages.contains(renamedPackageName)
10352                || pkg.packageName.equals(renamedPackageName)) {
10353            return;
10354        }
10355        pkg.setPackageName(renamedPackageName);
10356    }
10357
10358    /**
10359     * Just scans the package without any side effects.
10360     * <p>Not entirely true at the moment. There is still one side effect -- this
10361     * method potentially modifies a live {@link PackageSetting} object representing
10362     * the package being scanned. This will be resolved in the future.
10363     *
10364     * @param request Information about the package to be scanned
10365     * @param isUnderFactoryTest Whether or not the device is under factory test
10366     * @param currentTime The current time, in millis
10367     * @return The results of the scan
10368     */
10369    @GuardedBy("mInstallLock")
10370    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10371            boolean isUnderFactoryTest, long currentTime)
10372                    throws PackageManagerException {
10373        final PackageParser.Package pkg = request.pkg;
10374        PackageSetting pkgSetting = request.pkgSetting;
10375        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10376        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10377        final @ParseFlags int parseFlags = request.parseFlags;
10378        final @ScanFlags int scanFlags = request.scanFlags;
10379        final String realPkgName = request.realPkgName;
10380        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10381        final UserHandle user = request.user;
10382        final boolean isPlatformPackage = request.isPlatformPackage;
10383
10384        List<String> changedAbiCodePath = null;
10385
10386        if (DEBUG_PACKAGE_SCANNING) {
10387            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10388                Log.d(TAG, "Scanning package " + pkg.packageName);
10389        }
10390
10391        if (Build.IS_DEBUGGABLE &&
10392                pkg.isPrivileged() &&
10393                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10394            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10395        }
10396
10397        // Initialize package source and resource directories
10398        final File scanFile = new File(pkg.codePath);
10399        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10400        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10401
10402        // We keep references to the derived CPU Abis from settings in oder to reuse
10403        // them in the case where we're not upgrading or booting for the first time.
10404        String primaryCpuAbiFromSettings = null;
10405        String secondaryCpuAbiFromSettings = null;
10406        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10407
10408        if (!needToDeriveAbi) {
10409            if (pkgSetting != null) {
10410                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10411                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10412            } else {
10413                // Re-scanning a system package after uninstalling updates; need to derive ABI
10414                needToDeriveAbi = true;
10415            }
10416        }
10417
10418        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10419            PackageManagerService.reportSettingsProblem(Log.WARN,
10420                    "Package " + pkg.packageName + " shared user changed from "
10421                            + (pkgSetting.sharedUser != null
10422                            ? pkgSetting.sharedUser.name : "<nothing>")
10423                            + " to "
10424                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10425                            + "; replacing with new");
10426            pkgSetting = null;
10427        }
10428
10429        String[] usesStaticLibraries = null;
10430        if (pkg.usesStaticLibraries != null) {
10431            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10432            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10433        }
10434        final boolean createNewPackage = (pkgSetting == null);
10435        if (createNewPackage) {
10436            final String parentPackageName = (pkg.parentPackage != null)
10437                    ? pkg.parentPackage.packageName : null;
10438            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10439            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10440            // REMOVE SharedUserSetting from method; update in a separate call
10441            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10442                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10443                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10444                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10445                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10446                    user, true /*allowInstall*/, instantApp, virtualPreload,
10447                    parentPackageName, pkg.getChildPackageNames(),
10448                    UserManagerService.getInstance(), usesStaticLibraries,
10449                    pkg.usesStaticLibrariesVersions);
10450        } else {
10451            // REMOVE SharedUserSetting from method; update in a separate call.
10452            //
10453            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10454            // secondaryCpuAbi are not known at this point so we always update them
10455            // to null here, only to reset them at a later point.
10456            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10457                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10458                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10459                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10460                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10461                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10462        }
10463        if (createNewPackage && originalPkgSetting != null) {
10464            // This is the initial transition from the original package, so,
10465            // fix up the new package's name now. We must do this after looking
10466            // up the package under its new name, so getPackageLP takes care of
10467            // fiddling things correctly.
10468            pkg.setPackageName(originalPkgSetting.name);
10469
10470            // File a report about this.
10471            String msg = "New package " + pkgSetting.realName
10472                    + " renamed to replace old package " + pkgSetting.name;
10473            reportSettingsProblem(Log.WARN, msg);
10474        }
10475
10476        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10477        // for existing packages, change the install state; but, only if it's explicitly specified
10478        if (!createNewPackage) {
10479            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10480            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10481            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10482        }
10483
10484        if (disabledPkgSetting != null) {
10485            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10486        }
10487
10488        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10489        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10490        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10491        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10492        // least restrictive selinux domain.
10493        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10494        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10495        // ensures that all packages continue to run in the same selinux domain.
10496        final int targetSdkVersion =
10497            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10498            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10499        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10500        // They currently can be if the sharedUser apps are signed with the platform key.
10501        final boolean isPrivileged = (sharedUserSetting != null) ?
10502            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10503
10504        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10505                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10506        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10507                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10508
10509        pkg.mExtras = pkgSetting;
10510        pkg.applicationInfo.processName = fixProcessName(
10511                pkg.applicationInfo.packageName,
10512                pkg.applicationInfo.processName);
10513
10514        if (!isPlatformPackage) {
10515            // Get all of our default paths setup
10516            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10517        }
10518
10519        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10520
10521        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10522            if (needToDeriveAbi) {
10523                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10524                final boolean extractNativeLibs = !pkg.isLibrary();
10525                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10526                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10527
10528                // Some system apps still use directory structure for native libraries
10529                // in which case we might end up not detecting abi solely based on apk
10530                // structure. Try to detect abi based on directory structure.
10531                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10532                        pkg.applicationInfo.primaryCpuAbi == null) {
10533                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10534                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10535                }
10536            } else {
10537                // This is not a first boot or an upgrade, don't bother deriving the
10538                // ABI during the scan. Instead, trust the value that was stored in the
10539                // package setting.
10540                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10541                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10542
10543                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10544
10545                if (DEBUG_ABI_SELECTION) {
10546                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10547                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10548                            pkg.applicationInfo.secondaryCpuAbi);
10549                }
10550            }
10551        } else {
10552            if ((scanFlags & SCAN_MOVE) != 0) {
10553                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10554                // but we already have this packages package info in the PackageSetting. We just
10555                // use that and derive the native library path based on the new codepath.
10556                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10557                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10558            }
10559
10560            // Set native library paths again. For moves, the path will be updated based on the
10561            // ABIs we've determined above. For non-moves, the path will be updated based on the
10562            // ABIs we determined during compilation, but the path will depend on the final
10563            // package path (after the rename away from the stage path).
10564            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10565        }
10566
10567        // This is a special case for the "system" package, where the ABI is
10568        // dictated by the zygote configuration (and init.rc). We should keep track
10569        // of this ABI so that we can deal with "normal" applications that run under
10570        // the same UID correctly.
10571        if (isPlatformPackage) {
10572            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10573                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10574        }
10575
10576        // If there's a mismatch between the abi-override in the package setting
10577        // and the abiOverride specified for the install. Warn about this because we
10578        // would've already compiled the app without taking the package setting into
10579        // account.
10580        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10581            if (cpuAbiOverride == null && pkg.packageName != null) {
10582                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10583                        " for package " + pkg.packageName);
10584            }
10585        }
10586
10587        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10588        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10589        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10590
10591        // Copy the derived override back to the parsed package, so that we can
10592        // update the package settings accordingly.
10593        pkg.cpuAbiOverride = cpuAbiOverride;
10594
10595        if (DEBUG_ABI_SELECTION) {
10596            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10597                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10598                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10599        }
10600
10601        // Push the derived path down into PackageSettings so we know what to
10602        // clean up at uninstall time.
10603        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10604
10605        if (DEBUG_ABI_SELECTION) {
10606            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10607                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10608                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10609        }
10610
10611        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10612            // We don't do this here during boot because we can do it all
10613            // at once after scanning all existing packages.
10614            //
10615            // We also do this *before* we perform dexopt on this package, so that
10616            // we can avoid redundant dexopts, and also to make sure we've got the
10617            // code and package path correct.
10618            changedAbiCodePath =
10619                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10620        }
10621
10622        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10623                android.Manifest.permission.FACTORY_TEST)) {
10624            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10625        }
10626
10627        if (isSystemApp(pkg)) {
10628            pkgSetting.isOrphaned = true;
10629        }
10630
10631        // Take care of first install / last update times.
10632        final long scanFileTime = getLastModifiedTime(pkg);
10633        if (currentTime != 0) {
10634            if (pkgSetting.firstInstallTime == 0) {
10635                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10636            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10637                pkgSetting.lastUpdateTime = currentTime;
10638            }
10639        } else if (pkgSetting.firstInstallTime == 0) {
10640            // We need *something*.  Take time time stamp of the file.
10641            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10642        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10643            if (scanFileTime != pkgSetting.timeStamp) {
10644                // A package on the system image has changed; consider this
10645                // to be an update.
10646                pkgSetting.lastUpdateTime = scanFileTime;
10647            }
10648        }
10649        pkgSetting.setTimeStamp(scanFileTime);
10650
10651        pkgSetting.pkg = pkg;
10652        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10653        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10654            pkgSetting.versionCode = pkg.getLongVersionCode();
10655        }
10656        // Update volume if needed
10657        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10658        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10659            Slog.i(PackageManagerService.TAG,
10660                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10661                    + " package " + pkg.packageName
10662                    + " volume from " + pkgSetting.volumeUuid
10663                    + " to " + volumeUuid);
10664            pkgSetting.volumeUuid = volumeUuid;
10665        }
10666
10667        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10668    }
10669
10670    /**
10671     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10672     */
10673    private static boolean apkHasCode(String fileName) {
10674        StrictJarFile jarFile = null;
10675        try {
10676            jarFile = new StrictJarFile(fileName,
10677                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10678            return jarFile.findEntry("classes.dex") != null;
10679        } catch (IOException ignore) {
10680        } finally {
10681            try {
10682                if (jarFile != null) {
10683                    jarFile.close();
10684                }
10685            } catch (IOException ignore) {}
10686        }
10687        return false;
10688    }
10689
10690    /**
10691     * Enforces code policy for the package. This ensures that if an APK has
10692     * declared hasCode="true" in its manifest that the APK actually contains
10693     * code.
10694     *
10695     * @throws PackageManagerException If bytecode could not be found when it should exist
10696     */
10697    private static void assertCodePolicy(PackageParser.Package pkg)
10698            throws PackageManagerException {
10699        final boolean shouldHaveCode =
10700                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10701        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10702            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10703                    "Package " + pkg.baseCodePath + " code is missing");
10704        }
10705
10706        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10707            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10708                final boolean splitShouldHaveCode =
10709                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10710                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10711                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10712                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10713                }
10714            }
10715        }
10716    }
10717
10718    /**
10719     * Applies policy to the parsed package based upon the given policy flags.
10720     * Ensures the package is in a good state.
10721     * <p>
10722     * Implementation detail: This method must NOT have any side effect. It would
10723     * ideally be static, but, it requires locks to read system state.
10724     */
10725    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10726            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10727        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10728            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10729            if (pkg.applicationInfo.isDirectBootAware()) {
10730                // we're direct boot aware; set for all components
10731                for (PackageParser.Service s : pkg.services) {
10732                    s.info.encryptionAware = s.info.directBootAware = true;
10733                }
10734                for (PackageParser.Provider p : pkg.providers) {
10735                    p.info.encryptionAware = p.info.directBootAware = true;
10736                }
10737                for (PackageParser.Activity a : pkg.activities) {
10738                    a.info.encryptionAware = a.info.directBootAware = true;
10739                }
10740                for (PackageParser.Activity r : pkg.receivers) {
10741                    r.info.encryptionAware = r.info.directBootAware = true;
10742                }
10743            }
10744            if (compressedFileExists(pkg.codePath)) {
10745                pkg.isStub = true;
10746            }
10747        } else {
10748            // non system apps can't be flagged as core
10749            pkg.coreApp = false;
10750            // clear flags not applicable to regular apps
10751            pkg.applicationInfo.flags &=
10752                    ~ApplicationInfo.FLAG_PERSISTENT;
10753            pkg.applicationInfo.privateFlags &=
10754                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10755            pkg.applicationInfo.privateFlags &=
10756                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10757            // cap permission priorities
10758            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10759                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10760                    pkg.permissionGroups.get(i).info.priority = 0;
10761                }
10762            }
10763        }
10764        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10765            // clear protected broadcasts
10766            pkg.protectedBroadcasts = null;
10767            // ignore export request for single user receivers
10768            if (pkg.receivers != null) {
10769                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10770                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10771                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10772                        receiver.info.exported = false;
10773                    }
10774                }
10775            }
10776            // ignore export request for single user services
10777            if (pkg.services != null) {
10778                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10779                    final PackageParser.Service service = pkg.services.get(i);
10780                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10781                        service.info.exported = false;
10782                    }
10783                }
10784            }
10785            // ignore export request for single user providers
10786            if (pkg.providers != null) {
10787                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10788                    final PackageParser.Provider provider = pkg.providers.get(i);
10789                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10790                        provider.info.exported = false;
10791                    }
10792                }
10793            }
10794        }
10795
10796        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10797            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10798        }
10799
10800        if ((scanFlags & SCAN_AS_OEM) != 0) {
10801            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10802        }
10803
10804        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10805            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10806        }
10807
10808        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10809            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10810        }
10811
10812        // Check if the package is signed with the same key as the platform package.
10813        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10814                (platformPkg != null && compareSignatures(
10815                        platformPkg.mSigningDetails.signatures,
10816                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10817            pkg.applicationInfo.privateFlags |=
10818                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10819        }
10820
10821        if (!isSystemApp(pkg)) {
10822            // Only system apps can use these features.
10823            pkg.mOriginalPackages = null;
10824            pkg.mRealPackage = null;
10825            pkg.mAdoptPermissions = null;
10826        }
10827    }
10828
10829    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10830            throws PackageManagerException {
10831        if (object == null) {
10832            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10833        }
10834        return object;
10835    }
10836
10837    /**
10838     * Asserts the parsed package is valid according to the given policy. If the
10839     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10840     * <p>
10841     * Implementation detail: This method must NOT have any side effects. It would
10842     * ideally be static, but, it requires locks to read system state.
10843     *
10844     * @throws PackageManagerException If the package fails any of the validation checks
10845     */
10846    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10847            final @ScanFlags int scanFlags)
10848                    throws PackageManagerException {
10849        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10850            assertCodePolicy(pkg);
10851        }
10852
10853        if (pkg.applicationInfo.getCodePath() == null ||
10854                pkg.applicationInfo.getResourcePath() == null) {
10855            // Bail out. The resource and code paths haven't been set.
10856            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10857                    "Code and resource paths haven't been set correctly");
10858        }
10859
10860        // Make sure we're not adding any bogus keyset info
10861        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10862        ksms.assertScannedPackageValid(pkg);
10863
10864        synchronized (mPackages) {
10865            // The special "android" package can only be defined once
10866            if (pkg.packageName.equals("android")) {
10867                if (mAndroidApplication != null) {
10868                    Slog.w(TAG, "*************************************************");
10869                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10870                    Slog.w(TAG, " codePath=" + pkg.codePath);
10871                    Slog.w(TAG, "*************************************************");
10872                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10873                            "Core android package being redefined.  Skipping.");
10874                }
10875            }
10876
10877            // A package name must be unique; don't allow duplicates
10878            if (mPackages.containsKey(pkg.packageName)) {
10879                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10880                        "Application package " + pkg.packageName
10881                        + " already installed.  Skipping duplicate.");
10882            }
10883
10884            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10885                // Static libs have a synthetic package name containing the version
10886                // but we still want the base name to be unique.
10887                if (mPackages.containsKey(pkg.manifestPackageName)) {
10888                    throw new PackageManagerException(
10889                            "Duplicate static shared lib provider package");
10890                }
10891
10892                // Static shared libraries should have at least O target SDK
10893                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10894                    throw new PackageManagerException(
10895                            "Packages declaring static-shared libs must target O SDK or higher");
10896                }
10897
10898                // Package declaring static a shared lib cannot be instant apps
10899                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10900                    throw new PackageManagerException(
10901                            "Packages declaring static-shared libs cannot be instant apps");
10902                }
10903
10904                // Package declaring static a shared lib cannot be renamed since the package
10905                // name is synthetic and apps can't code around package manager internals.
10906                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10907                    throw new PackageManagerException(
10908                            "Packages declaring static-shared libs cannot be renamed");
10909                }
10910
10911                // Package declaring static a shared lib cannot declare child packages
10912                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10913                    throw new PackageManagerException(
10914                            "Packages declaring static-shared libs cannot have child packages");
10915                }
10916
10917                // Package declaring static a shared lib cannot declare dynamic libs
10918                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10919                    throw new PackageManagerException(
10920                            "Packages declaring static-shared libs cannot declare dynamic libs");
10921                }
10922
10923                // Package declaring static a shared lib cannot declare shared users
10924                if (pkg.mSharedUserId != null) {
10925                    throw new PackageManagerException(
10926                            "Packages declaring static-shared libs cannot declare shared users");
10927                }
10928
10929                // Static shared libs cannot declare activities
10930                if (!pkg.activities.isEmpty()) {
10931                    throw new PackageManagerException(
10932                            "Static shared libs cannot declare activities");
10933                }
10934
10935                // Static shared libs cannot declare services
10936                if (!pkg.services.isEmpty()) {
10937                    throw new PackageManagerException(
10938                            "Static shared libs cannot declare services");
10939                }
10940
10941                // Static shared libs cannot declare providers
10942                if (!pkg.providers.isEmpty()) {
10943                    throw new PackageManagerException(
10944                            "Static shared libs cannot declare content providers");
10945                }
10946
10947                // Static shared libs cannot declare receivers
10948                if (!pkg.receivers.isEmpty()) {
10949                    throw new PackageManagerException(
10950                            "Static shared libs cannot declare broadcast receivers");
10951                }
10952
10953                // Static shared libs cannot declare permission groups
10954                if (!pkg.permissionGroups.isEmpty()) {
10955                    throw new PackageManagerException(
10956                            "Static shared libs cannot declare permission groups");
10957                }
10958
10959                // Static shared libs cannot declare permissions
10960                if (!pkg.permissions.isEmpty()) {
10961                    throw new PackageManagerException(
10962                            "Static shared libs cannot declare permissions");
10963                }
10964
10965                // Static shared libs cannot declare protected broadcasts
10966                if (pkg.protectedBroadcasts != null) {
10967                    throw new PackageManagerException(
10968                            "Static shared libs cannot declare protected broadcasts");
10969                }
10970
10971                // Static shared libs cannot be overlay targets
10972                if (pkg.mOverlayTarget != null) {
10973                    throw new PackageManagerException(
10974                            "Static shared libs cannot be overlay targets");
10975                }
10976
10977                // The version codes must be ordered as lib versions
10978                long minVersionCode = Long.MIN_VALUE;
10979                long maxVersionCode = Long.MAX_VALUE;
10980
10981                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10982                        pkg.staticSharedLibName);
10983                if (versionedLib != null) {
10984                    final int versionCount = versionedLib.size();
10985                    for (int i = 0; i < versionCount; i++) {
10986                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10987                        final long libVersionCode = libInfo.getDeclaringPackage()
10988                                .getLongVersionCode();
10989                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10990                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10991                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10992                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10993                        } else {
10994                            minVersionCode = maxVersionCode = libVersionCode;
10995                            break;
10996                        }
10997                    }
10998                }
10999                if (pkg.getLongVersionCode() < minVersionCode
11000                        || pkg.getLongVersionCode() > maxVersionCode) {
11001                    throw new PackageManagerException("Static shared"
11002                            + " lib version codes must be ordered as lib versions");
11003                }
11004            }
11005
11006            // Only privileged apps and updated privileged apps can add child packages.
11007            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11008                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
11009                    throw new PackageManagerException("Only privileged apps can add child "
11010                            + "packages. Ignoring package " + pkg.packageName);
11011                }
11012                final int childCount = pkg.childPackages.size();
11013                for (int i = 0; i < childCount; i++) {
11014                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11015                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11016                            childPkg.packageName)) {
11017                        throw new PackageManagerException("Can't override child of "
11018                                + "another disabled app. Ignoring package " + pkg.packageName);
11019                    }
11020                }
11021            }
11022
11023            // If we're only installing presumed-existing packages, require that the
11024            // scanned APK is both already known and at the path previously established
11025            // for it.  Previously unknown packages we pick up normally, but if we have an
11026            // a priori expectation about this package's install presence, enforce it.
11027            // With a singular exception for new system packages. When an OTA contains
11028            // a new system package, we allow the codepath to change from a system location
11029            // to the user-installed location. If we don't allow this change, any newer,
11030            // user-installed version of the application will be ignored.
11031            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11032                if (mExpectingBetter.containsKey(pkg.packageName)) {
11033                    logCriticalInfo(Log.WARN,
11034                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11035                } else {
11036                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11037                    if (known != null) {
11038                        if (DEBUG_PACKAGE_SCANNING) {
11039                            Log.d(TAG, "Examining " + pkg.codePath
11040                                    + " and requiring known paths " + known.codePathString
11041                                    + " & " + known.resourcePathString);
11042                        }
11043                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11044                                || !pkg.applicationInfo.getResourcePath().equals(
11045                                        known.resourcePathString)) {
11046                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11047                                    "Application package " + pkg.packageName
11048                                    + " found at " + pkg.applicationInfo.getCodePath()
11049                                    + " but expected at " + known.codePathString
11050                                    + "; ignoring.");
11051                        }
11052                    } else {
11053                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11054                                "Application package " + pkg.packageName
11055                                + " not found; ignoring.");
11056                    }
11057                }
11058            }
11059
11060            // Verify that this new package doesn't have any content providers
11061            // that conflict with existing packages.  Only do this if the
11062            // package isn't already installed, since we don't want to break
11063            // things that are installed.
11064            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11065                final int N = pkg.providers.size();
11066                int i;
11067                for (i=0; i<N; i++) {
11068                    PackageParser.Provider p = pkg.providers.get(i);
11069                    if (p.info.authority != null) {
11070                        String names[] = p.info.authority.split(";");
11071                        for (int j = 0; j < names.length; j++) {
11072                            if (mProvidersByAuthority.containsKey(names[j])) {
11073                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11074                                final String otherPackageName =
11075                                        ((other != null && other.getComponentName() != null) ?
11076                                                other.getComponentName().getPackageName() : "?");
11077                                throw new PackageManagerException(
11078                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11079                                        "Can't install because provider name " + names[j]
11080                                                + " (in package " + pkg.applicationInfo.packageName
11081                                                + ") is already used by " + otherPackageName);
11082                            }
11083                        }
11084                    }
11085                }
11086            }
11087
11088            // Verify that packages sharing a user with a privileged app are marked as privileged.
11089            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11090                SharedUserSetting sharedUserSetting = null;
11091                try {
11092                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11093                } catch (PackageManagerException ignore) {}
11094                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11095                    // Exempt SharedUsers signed with the platform key.
11096                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11097                    if ((platformPkgSetting.signatures.mSigningDetails
11098                            != PackageParser.SigningDetails.UNKNOWN)
11099                            && (compareSignatures(
11100                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11101                                    pkg.mSigningDetails.signatures)
11102                                            != PackageManager.SIGNATURE_MATCH)) {
11103                        throw new PackageManagerException("Apps that share a user with a " +
11104                                "privileged app must themselves be marked as privileged. " +
11105                                pkg.packageName + " shares privileged user " +
11106                                pkg.mSharedUserId + ".");
11107                    }
11108                }
11109            }
11110
11111            // Apply policies specific for runtime resource overlays (RROs).
11112            if (pkg.mOverlayTarget != null) {
11113                // System overlays have some restrictions on their use of the 'static' state.
11114                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11115                    // We are scanning a system overlay. This can be the first scan of the
11116                    // system/vendor/oem partition, or an update to the system overlay.
11117                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11118                        // This must be an update to a system overlay.
11119                        final PackageSetting previousPkg = assertNotNull(
11120                                mSettings.getPackageLPr(pkg.packageName),
11121                                "previous package state not present");
11122
11123                        // Static overlays cannot be updated.
11124                        if (previousPkg.pkg.mOverlayIsStatic) {
11125                            throw new PackageManagerException("Overlay " + pkg.packageName +
11126                                    " is static and cannot be upgraded.");
11127                        // Non-static overlays cannot be converted to static overlays.
11128                        } else if (pkg.mOverlayIsStatic) {
11129                            throw new PackageManagerException("Overlay " + pkg.packageName +
11130                                    " cannot be upgraded into a static overlay.");
11131                        }
11132                    }
11133                } else {
11134                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11135                    if (pkg.mOverlayIsStatic) {
11136                        throw new PackageManagerException("Overlay " + pkg.packageName +
11137                                " is static but not pre-installed.");
11138                    }
11139
11140                    // The only case where we allow installation of a non-system overlay is when
11141                    // its signature is signed with the platform certificate.
11142                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11143                    if ((platformPkgSetting.signatures.mSigningDetails
11144                            != PackageParser.SigningDetails.UNKNOWN)
11145                            && (compareSignatures(
11146                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11147                                    pkg.mSigningDetails.signatures)
11148                                            != PackageManager.SIGNATURE_MATCH)) {
11149                        throw new PackageManagerException("Overlay " + pkg.packageName +
11150                                " must be signed with the platform certificate.");
11151                    }
11152                }
11153            }
11154        }
11155    }
11156
11157    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11158            int type, String declaringPackageName, long declaringVersionCode) {
11159        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11160        if (versionedLib == null) {
11161            versionedLib = new LongSparseArray<>();
11162            mSharedLibraries.put(name, versionedLib);
11163            if (type == SharedLibraryInfo.TYPE_STATIC) {
11164                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11165            }
11166        } else if (versionedLib.indexOfKey(version) >= 0) {
11167            return false;
11168        }
11169        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11170                version, type, declaringPackageName, declaringVersionCode);
11171        versionedLib.put(version, libEntry);
11172        return true;
11173    }
11174
11175    private boolean removeSharedLibraryLPw(String name, long version) {
11176        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11177        if (versionedLib == null) {
11178            return false;
11179        }
11180        final int libIdx = versionedLib.indexOfKey(version);
11181        if (libIdx < 0) {
11182            return false;
11183        }
11184        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11185        versionedLib.remove(version);
11186        if (versionedLib.size() <= 0) {
11187            mSharedLibraries.remove(name);
11188            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11189                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11190                        .getPackageName());
11191            }
11192        }
11193        return true;
11194    }
11195
11196    /**
11197     * Adds a scanned package to the system. When this method is finished, the package will
11198     * be available for query, resolution, etc...
11199     */
11200    private void commitPackageSettings(PackageParser.Package pkg,
11201            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11202            final @ScanFlags int scanFlags, boolean chatty) {
11203        final String pkgName = pkg.packageName;
11204        if (mCustomResolverComponentName != null &&
11205                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11206            setUpCustomResolverActivity(pkg);
11207        }
11208
11209        if (pkg.packageName.equals("android")) {
11210            synchronized (mPackages) {
11211                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11212                    // Set up information for our fall-back user intent resolution activity.
11213                    mPlatformPackage = pkg;
11214                    pkg.mVersionCode = mSdkVersion;
11215                    pkg.mVersionCodeMajor = 0;
11216                    mAndroidApplication = pkg.applicationInfo;
11217                    if (!mResolverReplaced) {
11218                        mResolveActivity.applicationInfo = mAndroidApplication;
11219                        mResolveActivity.name = ResolverActivity.class.getName();
11220                        mResolveActivity.packageName = mAndroidApplication.packageName;
11221                        mResolveActivity.processName = "system:ui";
11222                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11223                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11224                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11225                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11226                        mResolveActivity.exported = true;
11227                        mResolveActivity.enabled = true;
11228                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11229                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11230                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11231                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11232                                | ActivityInfo.CONFIG_ORIENTATION
11233                                | ActivityInfo.CONFIG_KEYBOARD
11234                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11235                        mResolveInfo.activityInfo = mResolveActivity;
11236                        mResolveInfo.priority = 0;
11237                        mResolveInfo.preferredOrder = 0;
11238                        mResolveInfo.match = 0;
11239                        mResolveComponentName = new ComponentName(
11240                                mAndroidApplication.packageName, mResolveActivity.name);
11241                    }
11242                }
11243            }
11244        }
11245
11246        ArrayList<PackageParser.Package> clientLibPkgs = null;
11247        // writer
11248        synchronized (mPackages) {
11249            boolean hasStaticSharedLibs = false;
11250
11251            // Any app can add new static shared libraries
11252            if (pkg.staticSharedLibName != null) {
11253                // Static shared libs don't allow renaming as they have synthetic package
11254                // names to allow install of multiple versions, so use name from manifest.
11255                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11256                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11257                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11258                    hasStaticSharedLibs = true;
11259                } else {
11260                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11261                                + pkg.staticSharedLibName + " already exists; skipping");
11262                }
11263                // Static shared libs cannot be updated once installed since they
11264                // use synthetic package name which includes the version code, so
11265                // not need to update other packages's shared lib dependencies.
11266            }
11267
11268            if (!hasStaticSharedLibs
11269                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11270                // Only system apps can add new dynamic shared libraries.
11271                if (pkg.libraryNames != null) {
11272                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11273                        String name = pkg.libraryNames.get(i);
11274                        boolean allowed = false;
11275                        if (pkg.isUpdatedSystemApp()) {
11276                            // New library entries can only be added through the
11277                            // system image.  This is important to get rid of a lot
11278                            // of nasty edge cases: for example if we allowed a non-
11279                            // system update of the app to add a library, then uninstalling
11280                            // the update would make the library go away, and assumptions
11281                            // we made such as through app install filtering would now
11282                            // have allowed apps on the device which aren't compatible
11283                            // with it.  Better to just have the restriction here, be
11284                            // conservative, and create many fewer cases that can negatively
11285                            // impact the user experience.
11286                            final PackageSetting sysPs = mSettings
11287                                    .getDisabledSystemPkgLPr(pkg.packageName);
11288                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11289                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11290                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11291                                        allowed = true;
11292                                        break;
11293                                    }
11294                                }
11295                            }
11296                        } else {
11297                            allowed = true;
11298                        }
11299                        if (allowed) {
11300                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11301                                    SharedLibraryInfo.VERSION_UNDEFINED,
11302                                    SharedLibraryInfo.TYPE_DYNAMIC,
11303                                    pkg.packageName, pkg.getLongVersionCode())) {
11304                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11305                                        + name + " already exists; skipping");
11306                            }
11307                        } else {
11308                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11309                                    + name + " that is not declared on system image; skipping");
11310                        }
11311                    }
11312
11313                    if ((scanFlags & SCAN_BOOTING) == 0) {
11314                        // If we are not booting, we need to update any applications
11315                        // that are clients of our shared library.  If we are booting,
11316                        // this will all be done once the scan is complete.
11317                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11318                    }
11319                }
11320            }
11321        }
11322
11323        if ((scanFlags & SCAN_BOOTING) != 0) {
11324            // No apps can run during boot scan, so they don't need to be frozen
11325        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11326            // Caller asked to not kill app, so it's probably not frozen
11327        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11328            // Caller asked us to ignore frozen check for some reason; they
11329            // probably didn't know the package name
11330        } else {
11331            // We're doing major surgery on this package, so it better be frozen
11332            // right now to keep it from launching
11333            checkPackageFrozen(pkgName);
11334        }
11335
11336        // Also need to kill any apps that are dependent on the library.
11337        if (clientLibPkgs != null) {
11338            for (int i=0; i<clientLibPkgs.size(); i++) {
11339                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11340                killApplication(clientPkg.applicationInfo.packageName,
11341                        clientPkg.applicationInfo.uid, "update lib");
11342            }
11343        }
11344
11345        // writer
11346        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11347
11348        synchronized (mPackages) {
11349            // We don't expect installation to fail beyond this point
11350
11351            // Add the new setting to mSettings
11352            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11353            // Add the new setting to mPackages
11354            mPackages.put(pkg.applicationInfo.packageName, pkg);
11355            // Make sure we don't accidentally delete its data.
11356            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11357            while (iter.hasNext()) {
11358                PackageCleanItem item = iter.next();
11359                if (pkgName.equals(item.packageName)) {
11360                    iter.remove();
11361                }
11362            }
11363
11364            // Add the package's KeySets to the global KeySetManagerService
11365            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11366            ksms.addScannedPackageLPw(pkg);
11367
11368            int N = pkg.providers.size();
11369            StringBuilder r = null;
11370            int i;
11371            for (i=0; i<N; i++) {
11372                PackageParser.Provider p = pkg.providers.get(i);
11373                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11374                        p.info.processName);
11375                mProviders.addProvider(p);
11376                p.syncable = p.info.isSyncable;
11377                if (p.info.authority != null) {
11378                    String names[] = p.info.authority.split(";");
11379                    p.info.authority = null;
11380                    for (int j = 0; j < names.length; j++) {
11381                        if (j == 1 && p.syncable) {
11382                            // We only want the first authority for a provider to possibly be
11383                            // syncable, so if we already added this provider using a different
11384                            // authority clear the syncable flag. We copy the provider before
11385                            // changing it because the mProviders object contains a reference
11386                            // to a provider that we don't want to change.
11387                            // Only do this for the second authority since the resulting provider
11388                            // object can be the same for all future authorities for this provider.
11389                            p = new PackageParser.Provider(p);
11390                            p.syncable = false;
11391                        }
11392                        if (!mProvidersByAuthority.containsKey(names[j])) {
11393                            mProvidersByAuthority.put(names[j], p);
11394                            if (p.info.authority == null) {
11395                                p.info.authority = names[j];
11396                            } else {
11397                                p.info.authority = p.info.authority + ";" + names[j];
11398                            }
11399                            if (DEBUG_PACKAGE_SCANNING) {
11400                                if (chatty)
11401                                    Log.d(TAG, "Registered content provider: " + names[j]
11402                                            + ", className = " + p.info.name + ", isSyncable = "
11403                                            + p.info.isSyncable);
11404                            }
11405                        } else {
11406                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11407                            Slog.w(TAG, "Skipping provider name " + names[j] +
11408                                    " (in package " + pkg.applicationInfo.packageName +
11409                                    "): name already used by "
11410                                    + ((other != null && other.getComponentName() != null)
11411                                            ? other.getComponentName().getPackageName() : "?"));
11412                        }
11413                    }
11414                }
11415                if (chatty) {
11416                    if (r == null) {
11417                        r = new StringBuilder(256);
11418                    } else {
11419                        r.append(' ');
11420                    }
11421                    r.append(p.info.name);
11422                }
11423            }
11424            if (r != null) {
11425                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11426            }
11427
11428            N = pkg.services.size();
11429            r = null;
11430            for (i=0; i<N; i++) {
11431                PackageParser.Service s = pkg.services.get(i);
11432                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11433                        s.info.processName);
11434                mServices.addService(s);
11435                if (chatty) {
11436                    if (r == null) {
11437                        r = new StringBuilder(256);
11438                    } else {
11439                        r.append(' ');
11440                    }
11441                    r.append(s.info.name);
11442                }
11443            }
11444            if (r != null) {
11445                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11446            }
11447
11448            N = pkg.receivers.size();
11449            r = null;
11450            for (i=0; i<N; i++) {
11451                PackageParser.Activity a = pkg.receivers.get(i);
11452                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11453                        a.info.processName);
11454                mReceivers.addActivity(a, "receiver");
11455                if (chatty) {
11456                    if (r == null) {
11457                        r = new StringBuilder(256);
11458                    } else {
11459                        r.append(' ');
11460                    }
11461                    r.append(a.info.name);
11462                }
11463            }
11464            if (r != null) {
11465                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11466            }
11467
11468            N = pkg.activities.size();
11469            r = null;
11470            for (i=0; i<N; i++) {
11471                PackageParser.Activity a = pkg.activities.get(i);
11472                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11473                        a.info.processName);
11474                mActivities.addActivity(a, "activity");
11475                if (chatty) {
11476                    if (r == null) {
11477                        r = new StringBuilder(256);
11478                    } else {
11479                        r.append(' ');
11480                    }
11481                    r.append(a.info.name);
11482                }
11483            }
11484            if (r != null) {
11485                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11486            }
11487
11488            // Don't allow ephemeral applications to define new permissions groups.
11489            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11490                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11491                        + " ignored: instant apps cannot define new permission groups.");
11492            } else {
11493                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11494            }
11495
11496            // Don't allow ephemeral applications to define new permissions.
11497            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11498                Slog.w(TAG, "Permissions from package " + pkg.packageName
11499                        + " ignored: instant apps cannot define new permissions.");
11500            } else {
11501                mPermissionManager.addAllPermissions(pkg, chatty);
11502            }
11503
11504            N = pkg.instrumentation.size();
11505            r = null;
11506            for (i=0; i<N; i++) {
11507                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11508                a.info.packageName = pkg.applicationInfo.packageName;
11509                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11510                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11511                a.info.splitNames = pkg.splitNames;
11512                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11513                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11514                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11515                a.info.dataDir = pkg.applicationInfo.dataDir;
11516                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11517                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11518                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11519                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11520                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11521                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11522                mInstrumentation.put(a.getComponentName(), a);
11523                if (chatty) {
11524                    if (r == null) {
11525                        r = new StringBuilder(256);
11526                    } else {
11527                        r.append(' ');
11528                    }
11529                    r.append(a.info.name);
11530                }
11531            }
11532            if (r != null) {
11533                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11534            }
11535
11536            if (pkg.protectedBroadcasts != null) {
11537                N = pkg.protectedBroadcasts.size();
11538                synchronized (mProtectedBroadcasts) {
11539                    for (i = 0; i < N; i++) {
11540                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11541                    }
11542                }
11543            }
11544
11545            if (oldPkg != null) {
11546                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11547                // revoke callbacks from this method might need to kill apps which need the
11548                // mPackages lock on a different thread. This would dead lock.
11549                //
11550                // Hence create a copy of all package names and pass it into
11551                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11552                // revoked. If a new package is added before the async code runs the permission
11553                // won't be granted yet, hence new packages are no problem.
11554                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11555
11556                AsyncTask.execute(() ->
11557                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11558                                allPackageNames, mPermissionCallback));
11559            }
11560        }
11561
11562        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11563    }
11564
11565    /**
11566     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11567     * is derived purely on the basis of the contents of {@code scanFile} and
11568     * {@code cpuAbiOverride}.
11569     *
11570     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11571     */
11572    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11573            boolean extractLibs)
11574                    throws PackageManagerException {
11575        // Give ourselves some initial paths; we'll come back for another
11576        // pass once we've determined ABI below.
11577        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11578
11579        // We would never need to extract libs for forward-locked and external packages,
11580        // since the container service will do it for us. We shouldn't attempt to
11581        // extract libs from system app when it was not updated.
11582        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11583                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11584            extractLibs = false;
11585        }
11586
11587        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11588        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11589
11590        NativeLibraryHelper.Handle handle = null;
11591        try {
11592            handle = NativeLibraryHelper.Handle.create(pkg);
11593            // TODO(multiArch): This can be null for apps that didn't go through the
11594            // usual installation process. We can calculate it again, like we
11595            // do during install time.
11596            //
11597            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11598            // unnecessary.
11599            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11600
11601            // Null out the abis so that they can be recalculated.
11602            pkg.applicationInfo.primaryCpuAbi = null;
11603            pkg.applicationInfo.secondaryCpuAbi = null;
11604            if (isMultiArch(pkg.applicationInfo)) {
11605                // Warn if we've set an abiOverride for multi-lib packages..
11606                // By definition, we need to copy both 32 and 64 bit libraries for
11607                // such packages.
11608                if (pkg.cpuAbiOverride != null
11609                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11610                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11611                }
11612
11613                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11614                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11615                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11616                    if (extractLibs) {
11617                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11618                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11619                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11620                                useIsaSpecificSubdirs);
11621                    } else {
11622                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11623                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11624                    }
11625                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11626                }
11627
11628                // Shared library native code should be in the APK zip aligned
11629                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11630                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11631                            "Shared library native lib extraction not supported");
11632                }
11633
11634                maybeThrowExceptionForMultiArchCopy(
11635                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11636
11637                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11638                    if (extractLibs) {
11639                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11640                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11641                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11642                                useIsaSpecificSubdirs);
11643                    } else {
11644                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11645                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11646                    }
11647                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11648                }
11649
11650                maybeThrowExceptionForMultiArchCopy(
11651                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11652
11653                if (abi64 >= 0) {
11654                    // Shared library native libs should be in the APK zip aligned
11655                    if (extractLibs && pkg.isLibrary()) {
11656                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11657                                "Shared library native lib extraction not supported");
11658                    }
11659                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11660                }
11661
11662                if (abi32 >= 0) {
11663                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11664                    if (abi64 >= 0) {
11665                        if (pkg.use32bitAbi) {
11666                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11667                            pkg.applicationInfo.primaryCpuAbi = abi;
11668                        } else {
11669                            pkg.applicationInfo.secondaryCpuAbi = abi;
11670                        }
11671                    } else {
11672                        pkg.applicationInfo.primaryCpuAbi = abi;
11673                    }
11674                }
11675            } else {
11676                String[] abiList = (cpuAbiOverride != null) ?
11677                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11678
11679                // Enable gross and lame hacks for apps that are built with old
11680                // SDK tools. We must scan their APKs for renderscript bitcode and
11681                // not launch them if it's present. Don't bother checking on devices
11682                // that don't have 64 bit support.
11683                boolean needsRenderScriptOverride = false;
11684                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11685                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11686                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11687                    needsRenderScriptOverride = true;
11688                }
11689
11690                final int copyRet;
11691                if (extractLibs) {
11692                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11693                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11694                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11695                } else {
11696                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11697                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11698                }
11699                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11700
11701                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11702                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11703                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11704                }
11705
11706                if (copyRet >= 0) {
11707                    // Shared libraries that have native libs must be multi-architecture
11708                    if (pkg.isLibrary()) {
11709                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11710                                "Shared library with native libs must be multiarch");
11711                    }
11712                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11713                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11714                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11715                } else if (needsRenderScriptOverride) {
11716                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11717                }
11718            }
11719        } catch (IOException ioe) {
11720            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11721        } finally {
11722            IoUtils.closeQuietly(handle);
11723        }
11724
11725        // Now that we've calculated the ABIs and determined if it's an internal app,
11726        // we will go ahead and populate the nativeLibraryPath.
11727        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11728    }
11729
11730    /**
11731     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11732     * i.e, so that all packages can be run inside a single process if required.
11733     *
11734     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11735     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11736     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11737     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11738     * updating a package that belongs to a shared user.
11739     *
11740     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11741     * adds unnecessary complexity.
11742     */
11743    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11744            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11745        List<String> changedAbiCodePath = null;
11746        String requiredInstructionSet = null;
11747        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11748            requiredInstructionSet = VMRuntime.getInstructionSet(
11749                     scannedPackage.applicationInfo.primaryCpuAbi);
11750        }
11751
11752        PackageSetting requirer = null;
11753        for (PackageSetting ps : packagesForUser) {
11754            // If packagesForUser contains scannedPackage, we skip it. This will happen
11755            // when scannedPackage is an update of an existing package. Without this check,
11756            // we will never be able to change the ABI of any package belonging to a shared
11757            // user, even if it's compatible with other packages.
11758            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11759                if (ps.primaryCpuAbiString == null) {
11760                    continue;
11761                }
11762
11763                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11764                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11765                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11766                    // this but there's not much we can do.
11767                    String errorMessage = "Instruction set mismatch, "
11768                            + ((requirer == null) ? "[caller]" : requirer)
11769                            + " requires " + requiredInstructionSet + " whereas " + ps
11770                            + " requires " + instructionSet;
11771                    Slog.w(TAG, errorMessage);
11772                }
11773
11774                if (requiredInstructionSet == null) {
11775                    requiredInstructionSet = instructionSet;
11776                    requirer = ps;
11777                }
11778            }
11779        }
11780
11781        if (requiredInstructionSet != null) {
11782            String adjustedAbi;
11783            if (requirer != null) {
11784                // requirer != null implies that either scannedPackage was null or that scannedPackage
11785                // did not require an ABI, in which case we have to adjust scannedPackage to match
11786                // the ABI of the set (which is the same as requirer's ABI)
11787                adjustedAbi = requirer.primaryCpuAbiString;
11788                if (scannedPackage != null) {
11789                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11790                }
11791            } else {
11792                // requirer == null implies that we're updating all ABIs in the set to
11793                // match scannedPackage.
11794                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11795            }
11796
11797            for (PackageSetting ps : packagesForUser) {
11798                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11799                    if (ps.primaryCpuAbiString != null) {
11800                        continue;
11801                    }
11802
11803                    ps.primaryCpuAbiString = adjustedAbi;
11804                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11805                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11806                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11807                        if (DEBUG_ABI_SELECTION) {
11808                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11809                                    + " (requirer="
11810                                    + (requirer != null ? requirer.pkg : "null")
11811                                    + ", scannedPackage="
11812                                    + (scannedPackage != null ? scannedPackage : "null")
11813                                    + ")");
11814                        }
11815                        if (changedAbiCodePath == null) {
11816                            changedAbiCodePath = new ArrayList<>();
11817                        }
11818                        changedAbiCodePath.add(ps.codePathString);
11819                    }
11820                }
11821            }
11822        }
11823        return changedAbiCodePath;
11824    }
11825
11826    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11827        synchronized (mPackages) {
11828            mResolverReplaced = true;
11829            // Set up information for custom user intent resolution activity.
11830            mResolveActivity.applicationInfo = pkg.applicationInfo;
11831            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11832            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11833            mResolveActivity.processName = pkg.applicationInfo.packageName;
11834            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11835            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11836                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11837            mResolveActivity.theme = 0;
11838            mResolveActivity.exported = true;
11839            mResolveActivity.enabled = true;
11840            mResolveInfo.activityInfo = mResolveActivity;
11841            mResolveInfo.priority = 0;
11842            mResolveInfo.preferredOrder = 0;
11843            mResolveInfo.match = 0;
11844            mResolveComponentName = mCustomResolverComponentName;
11845            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11846                    mResolveComponentName);
11847        }
11848    }
11849
11850    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11851        if (installerActivity == null) {
11852            if (DEBUG_INSTANT) {
11853                Slog.d(TAG, "Clear ephemeral installer activity");
11854            }
11855            mInstantAppInstallerActivity = null;
11856            return;
11857        }
11858
11859        if (DEBUG_INSTANT) {
11860            Slog.d(TAG, "Set ephemeral installer activity: "
11861                    + installerActivity.getComponentName());
11862        }
11863        // Set up information for ephemeral installer activity
11864        mInstantAppInstallerActivity = installerActivity;
11865        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11866                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11867        mInstantAppInstallerActivity.exported = true;
11868        mInstantAppInstallerActivity.enabled = true;
11869        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11870        mInstantAppInstallerInfo.priority = 1;
11871        mInstantAppInstallerInfo.preferredOrder = 1;
11872        mInstantAppInstallerInfo.isDefault = true;
11873        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11874                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11875    }
11876
11877    private static String calculateBundledApkRoot(final String codePathString) {
11878        final File codePath = new File(codePathString);
11879        final File codeRoot;
11880        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11881            codeRoot = Environment.getRootDirectory();
11882        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11883            codeRoot = Environment.getOemDirectory();
11884        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11885            codeRoot = Environment.getVendorDirectory();
11886        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11887            codeRoot = Environment.getOdmDirectory();
11888        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11889            codeRoot = Environment.getProductDirectory();
11890        } else {
11891            // Unrecognized code path; take its top real segment as the apk root:
11892            // e.g. /something/app/blah.apk => /something
11893            try {
11894                File f = codePath.getCanonicalFile();
11895                File parent = f.getParentFile();    // non-null because codePath is a file
11896                File tmp;
11897                while ((tmp = parent.getParentFile()) != null) {
11898                    f = parent;
11899                    parent = tmp;
11900                }
11901                codeRoot = f;
11902                Slog.w(TAG, "Unrecognized code path "
11903                        + codePath + " - using " + codeRoot);
11904            } catch (IOException e) {
11905                // Can't canonicalize the code path -- shenanigans?
11906                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11907                return Environment.getRootDirectory().getPath();
11908            }
11909        }
11910        return codeRoot.getPath();
11911    }
11912
11913    /**
11914     * Derive and set the location of native libraries for the given package,
11915     * which varies depending on where and how the package was installed.
11916     */
11917    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11918        final ApplicationInfo info = pkg.applicationInfo;
11919        final String codePath = pkg.codePath;
11920        final File codeFile = new File(codePath);
11921        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11922        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11923
11924        info.nativeLibraryRootDir = null;
11925        info.nativeLibraryRootRequiresIsa = false;
11926        info.nativeLibraryDir = null;
11927        info.secondaryNativeLibraryDir = null;
11928
11929        if (isApkFile(codeFile)) {
11930            // Monolithic install
11931            if (bundledApp) {
11932                // If "/system/lib64/apkname" exists, assume that is the per-package
11933                // native library directory to use; otherwise use "/system/lib/apkname".
11934                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11935                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11936                        getPrimaryInstructionSet(info));
11937
11938                // This is a bundled system app so choose the path based on the ABI.
11939                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11940                // is just the default path.
11941                final String apkName = deriveCodePathName(codePath);
11942                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11943                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11944                        apkName).getAbsolutePath();
11945
11946                if (info.secondaryCpuAbi != null) {
11947                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11948                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11949                            secondaryLibDir, apkName).getAbsolutePath();
11950                }
11951            } else if (asecApp) {
11952                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11953                        .getAbsolutePath();
11954            } else {
11955                final String apkName = deriveCodePathName(codePath);
11956                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11957                        .getAbsolutePath();
11958            }
11959
11960            info.nativeLibraryRootRequiresIsa = false;
11961            info.nativeLibraryDir = info.nativeLibraryRootDir;
11962        } else {
11963            // Cluster install
11964            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11965            info.nativeLibraryRootRequiresIsa = true;
11966
11967            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11968                    getPrimaryInstructionSet(info)).getAbsolutePath();
11969
11970            if (info.secondaryCpuAbi != null) {
11971                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11972                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11973            }
11974        }
11975    }
11976
11977    /**
11978     * Calculate the abis and roots for a bundled app. These can uniquely
11979     * be determined from the contents of the system partition, i.e whether
11980     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11981     * of this information, and instead assume that the system was built
11982     * sensibly.
11983     */
11984    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11985                                           PackageSetting pkgSetting) {
11986        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11987
11988        // If "/system/lib64/apkname" exists, assume that is the per-package
11989        // native library directory to use; otherwise use "/system/lib/apkname".
11990        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11991        setBundledAppAbi(pkg, apkRoot, apkName);
11992        // pkgSetting might be null during rescan following uninstall of updates
11993        // to a bundled app, so accommodate that possibility.  The settings in
11994        // that case will be established later from the parsed package.
11995        //
11996        // If the settings aren't null, sync them up with what we've just derived.
11997        // note that apkRoot isn't stored in the package settings.
11998        if (pkgSetting != null) {
11999            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12000            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12001        }
12002    }
12003
12004    /**
12005     * Deduces the ABI of a bundled app and sets the relevant fields on the
12006     * parsed pkg object.
12007     *
12008     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12009     *        under which system libraries are installed.
12010     * @param apkName the name of the installed package.
12011     */
12012    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12013        final File codeFile = new File(pkg.codePath);
12014
12015        final boolean has64BitLibs;
12016        final boolean has32BitLibs;
12017        if (isApkFile(codeFile)) {
12018            // Monolithic install
12019            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12020            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12021        } else {
12022            // Cluster install
12023            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12024            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12025                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12026                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12027                has64BitLibs = (new File(rootDir, isa)).exists();
12028            } else {
12029                has64BitLibs = false;
12030            }
12031            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12032                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12033                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12034                has32BitLibs = (new File(rootDir, isa)).exists();
12035            } else {
12036                has32BitLibs = false;
12037            }
12038        }
12039
12040        if (has64BitLibs && !has32BitLibs) {
12041            // The package has 64 bit libs, but not 32 bit libs. Its primary
12042            // ABI should be 64 bit. We can safely assume here that the bundled
12043            // native libraries correspond to the most preferred ABI in the list.
12044
12045            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12046            pkg.applicationInfo.secondaryCpuAbi = null;
12047        } else if (has32BitLibs && !has64BitLibs) {
12048            // The package has 32 bit libs but not 64 bit libs. Its primary
12049            // ABI should be 32 bit.
12050
12051            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12052            pkg.applicationInfo.secondaryCpuAbi = null;
12053        } else if (has32BitLibs && has64BitLibs) {
12054            // The application has both 64 and 32 bit bundled libraries. We check
12055            // here that the app declares multiArch support, and warn if it doesn't.
12056            //
12057            // We will be lenient here and record both ABIs. The primary will be the
12058            // ABI that's higher on the list, i.e, a device that's configured to prefer
12059            // 64 bit apps will see a 64 bit primary ABI,
12060
12061            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12062                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12063            }
12064
12065            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12066                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12067                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12068            } else {
12069                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12070                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12071            }
12072        } else {
12073            pkg.applicationInfo.primaryCpuAbi = null;
12074            pkg.applicationInfo.secondaryCpuAbi = null;
12075        }
12076    }
12077
12078    private void killApplication(String pkgName, int appId, String reason) {
12079        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12080    }
12081
12082    private void killApplication(String pkgName, int appId, int userId, String reason) {
12083        // Request the ActivityManager to kill the process(only for existing packages)
12084        // so that we do not end up in a confused state while the user is still using the older
12085        // version of the application while the new one gets installed.
12086        final long token = Binder.clearCallingIdentity();
12087        try {
12088            IActivityManager am = ActivityManager.getService();
12089            if (am != null) {
12090                try {
12091                    am.killApplication(pkgName, appId, userId, reason);
12092                } catch (RemoteException e) {
12093                }
12094            }
12095        } finally {
12096            Binder.restoreCallingIdentity(token);
12097        }
12098    }
12099
12100    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12101        // Remove the parent package setting
12102        PackageSetting ps = (PackageSetting) pkg.mExtras;
12103        if (ps != null) {
12104            removePackageLI(ps, chatty);
12105        }
12106        // Remove the child package setting
12107        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12108        for (int i = 0; i < childCount; i++) {
12109            PackageParser.Package childPkg = pkg.childPackages.get(i);
12110            ps = (PackageSetting) childPkg.mExtras;
12111            if (ps != null) {
12112                removePackageLI(ps, chatty);
12113            }
12114        }
12115    }
12116
12117    void removePackageLI(PackageSetting ps, boolean chatty) {
12118        if (DEBUG_INSTALL) {
12119            if (chatty)
12120                Log.d(TAG, "Removing package " + ps.name);
12121        }
12122
12123        // writer
12124        synchronized (mPackages) {
12125            mPackages.remove(ps.name);
12126            final PackageParser.Package pkg = ps.pkg;
12127            if (pkg != null) {
12128                cleanPackageDataStructuresLILPw(pkg, chatty);
12129            }
12130        }
12131    }
12132
12133    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12134        if (DEBUG_INSTALL) {
12135            if (chatty)
12136                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12137        }
12138
12139        // writer
12140        synchronized (mPackages) {
12141            // Remove the parent package
12142            mPackages.remove(pkg.applicationInfo.packageName);
12143            cleanPackageDataStructuresLILPw(pkg, chatty);
12144
12145            // Remove the child packages
12146            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12147            for (int i = 0; i < childCount; i++) {
12148                PackageParser.Package childPkg = pkg.childPackages.get(i);
12149                mPackages.remove(childPkg.applicationInfo.packageName);
12150                cleanPackageDataStructuresLILPw(childPkg, chatty);
12151            }
12152        }
12153    }
12154
12155    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12156        int N = pkg.providers.size();
12157        StringBuilder r = null;
12158        int i;
12159        for (i=0; i<N; i++) {
12160            PackageParser.Provider p = pkg.providers.get(i);
12161            mProviders.removeProvider(p);
12162            if (p.info.authority == null) {
12163
12164                /* There was another ContentProvider with this authority when
12165                 * this app was installed so this authority is null,
12166                 * Ignore it as we don't have to unregister the provider.
12167                 */
12168                continue;
12169            }
12170            String names[] = p.info.authority.split(";");
12171            for (int j = 0; j < names.length; j++) {
12172                if (mProvidersByAuthority.get(names[j]) == p) {
12173                    mProvidersByAuthority.remove(names[j]);
12174                    if (DEBUG_REMOVE) {
12175                        if (chatty)
12176                            Log.d(TAG, "Unregistered content provider: " + names[j]
12177                                    + ", className = " + p.info.name + ", isSyncable = "
12178                                    + p.info.isSyncable);
12179                    }
12180                }
12181            }
12182            if (DEBUG_REMOVE && chatty) {
12183                if (r == null) {
12184                    r = new StringBuilder(256);
12185                } else {
12186                    r.append(' ');
12187                }
12188                r.append(p.info.name);
12189            }
12190        }
12191        if (r != null) {
12192            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12193        }
12194
12195        N = pkg.services.size();
12196        r = null;
12197        for (i=0; i<N; i++) {
12198            PackageParser.Service s = pkg.services.get(i);
12199            mServices.removeService(s);
12200            if (chatty) {
12201                if (r == null) {
12202                    r = new StringBuilder(256);
12203                } else {
12204                    r.append(' ');
12205                }
12206                r.append(s.info.name);
12207            }
12208        }
12209        if (r != null) {
12210            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12211        }
12212
12213        N = pkg.receivers.size();
12214        r = null;
12215        for (i=0; i<N; i++) {
12216            PackageParser.Activity a = pkg.receivers.get(i);
12217            mReceivers.removeActivity(a, "receiver");
12218            if (DEBUG_REMOVE && chatty) {
12219                if (r == null) {
12220                    r = new StringBuilder(256);
12221                } else {
12222                    r.append(' ');
12223                }
12224                r.append(a.info.name);
12225            }
12226        }
12227        if (r != null) {
12228            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12229        }
12230
12231        N = pkg.activities.size();
12232        r = null;
12233        for (i=0; i<N; i++) {
12234            PackageParser.Activity a = pkg.activities.get(i);
12235            mActivities.removeActivity(a, "activity");
12236            if (DEBUG_REMOVE && chatty) {
12237                if (r == null) {
12238                    r = new StringBuilder(256);
12239                } else {
12240                    r.append(' ');
12241                }
12242                r.append(a.info.name);
12243            }
12244        }
12245        if (r != null) {
12246            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12247        }
12248
12249        mPermissionManager.removeAllPermissions(pkg, chatty);
12250
12251        N = pkg.instrumentation.size();
12252        r = null;
12253        for (i=0; i<N; i++) {
12254            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12255            mInstrumentation.remove(a.getComponentName());
12256            if (DEBUG_REMOVE && chatty) {
12257                if (r == null) {
12258                    r = new StringBuilder(256);
12259                } else {
12260                    r.append(' ');
12261                }
12262                r.append(a.info.name);
12263            }
12264        }
12265        if (r != null) {
12266            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12267        }
12268
12269        r = null;
12270        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12271            // Only system apps can hold shared libraries.
12272            if (pkg.libraryNames != null) {
12273                for (i = 0; i < pkg.libraryNames.size(); i++) {
12274                    String name = pkg.libraryNames.get(i);
12275                    if (removeSharedLibraryLPw(name, 0)) {
12276                        if (DEBUG_REMOVE && chatty) {
12277                            if (r == null) {
12278                                r = new StringBuilder(256);
12279                            } else {
12280                                r.append(' ');
12281                            }
12282                            r.append(name);
12283                        }
12284                    }
12285                }
12286            }
12287        }
12288
12289        r = null;
12290
12291        // Any package can hold static shared libraries.
12292        if (pkg.staticSharedLibName != null) {
12293            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12294                if (DEBUG_REMOVE && chatty) {
12295                    if (r == null) {
12296                        r = new StringBuilder(256);
12297                    } else {
12298                        r.append(' ');
12299                    }
12300                    r.append(pkg.staticSharedLibName);
12301                }
12302            }
12303        }
12304
12305        if (r != null) {
12306            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12307        }
12308    }
12309
12310
12311    final class ActivityIntentResolver
12312            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12313        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12314                boolean defaultOnly, int userId) {
12315            if (!sUserManager.exists(userId)) return null;
12316            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12317            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12318        }
12319
12320        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12321                int userId) {
12322            if (!sUserManager.exists(userId)) return null;
12323            mFlags = flags;
12324            return super.queryIntent(intent, resolvedType,
12325                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12326                    userId);
12327        }
12328
12329        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12330                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12331            if (!sUserManager.exists(userId)) return null;
12332            if (packageActivities == null) {
12333                return null;
12334            }
12335            mFlags = flags;
12336            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12337            final int N = packageActivities.size();
12338            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12339                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12340
12341            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12342            for (int i = 0; i < N; ++i) {
12343                intentFilters = packageActivities.get(i).intents;
12344                if (intentFilters != null && intentFilters.size() > 0) {
12345                    PackageParser.ActivityIntentInfo[] array =
12346                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12347                    intentFilters.toArray(array);
12348                    listCut.add(array);
12349                }
12350            }
12351            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12352        }
12353
12354        /**
12355         * Finds a privileged activity that matches the specified activity names.
12356         */
12357        private PackageParser.Activity findMatchingActivity(
12358                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12359            for (PackageParser.Activity sysActivity : activityList) {
12360                if (sysActivity.info.name.equals(activityInfo.name)) {
12361                    return sysActivity;
12362                }
12363                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12364                    return sysActivity;
12365                }
12366                if (sysActivity.info.targetActivity != null) {
12367                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12368                        return sysActivity;
12369                    }
12370                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12371                        return sysActivity;
12372                    }
12373                }
12374            }
12375            return null;
12376        }
12377
12378        public class IterGenerator<E> {
12379            public Iterator<E> generate(ActivityIntentInfo info) {
12380                return null;
12381            }
12382        }
12383
12384        public class ActionIterGenerator extends IterGenerator<String> {
12385            @Override
12386            public Iterator<String> generate(ActivityIntentInfo info) {
12387                return info.actionsIterator();
12388            }
12389        }
12390
12391        public class CategoriesIterGenerator extends IterGenerator<String> {
12392            @Override
12393            public Iterator<String> generate(ActivityIntentInfo info) {
12394                return info.categoriesIterator();
12395            }
12396        }
12397
12398        public class SchemesIterGenerator extends IterGenerator<String> {
12399            @Override
12400            public Iterator<String> generate(ActivityIntentInfo info) {
12401                return info.schemesIterator();
12402            }
12403        }
12404
12405        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12406            @Override
12407            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12408                return info.authoritiesIterator();
12409            }
12410        }
12411
12412        /**
12413         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12414         * MODIFIED. Do not pass in a list that should not be changed.
12415         */
12416        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12417                IterGenerator<T> generator, Iterator<T> searchIterator) {
12418            // loop through the set of actions; every one must be found in the intent filter
12419            while (searchIterator.hasNext()) {
12420                // we must have at least one filter in the list to consider a match
12421                if (intentList.size() == 0) {
12422                    break;
12423                }
12424
12425                final T searchAction = searchIterator.next();
12426
12427                // loop through the set of intent filters
12428                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12429                while (intentIter.hasNext()) {
12430                    final ActivityIntentInfo intentInfo = intentIter.next();
12431                    boolean selectionFound = false;
12432
12433                    // loop through the intent filter's selection criteria; at least one
12434                    // of them must match the searched criteria
12435                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12436                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12437                        final T intentSelection = intentSelectionIter.next();
12438                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12439                            selectionFound = true;
12440                            break;
12441                        }
12442                    }
12443
12444                    // the selection criteria wasn't found in this filter's set; this filter
12445                    // is not a potential match
12446                    if (!selectionFound) {
12447                        intentIter.remove();
12448                    }
12449                }
12450            }
12451        }
12452
12453        private boolean isProtectedAction(ActivityIntentInfo filter) {
12454            final Iterator<String> actionsIter = filter.actionsIterator();
12455            while (actionsIter != null && actionsIter.hasNext()) {
12456                final String filterAction = actionsIter.next();
12457                if (PROTECTED_ACTIONS.contains(filterAction)) {
12458                    return true;
12459                }
12460            }
12461            return false;
12462        }
12463
12464        /**
12465         * Adjusts the priority of the given intent filter according to policy.
12466         * <p>
12467         * <ul>
12468         * <li>The priority for non privileged applications is capped to '0'</li>
12469         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12470         * <li>The priority for unbundled updates to privileged applications is capped to the
12471         *      priority defined on the system partition</li>
12472         * </ul>
12473         * <p>
12474         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12475         * allowed to obtain any priority on any action.
12476         */
12477        private void adjustPriority(
12478                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12479            // nothing to do; priority is fine as-is
12480            if (intent.getPriority() <= 0) {
12481                return;
12482            }
12483
12484            final ActivityInfo activityInfo = intent.activity.info;
12485            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12486
12487            final boolean privilegedApp =
12488                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12489            if (!privilegedApp) {
12490                // non-privileged applications can never define a priority >0
12491                if (DEBUG_FILTERS) {
12492                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12493                            + " package: " + applicationInfo.packageName
12494                            + " activity: " + intent.activity.className
12495                            + " origPrio: " + intent.getPriority());
12496                }
12497                intent.setPriority(0);
12498                return;
12499            }
12500
12501            if (systemActivities == null) {
12502                // the system package is not disabled; we're parsing the system partition
12503                if (isProtectedAction(intent)) {
12504                    if (mDeferProtectedFilters) {
12505                        // We can't deal with these just yet. No component should ever obtain a
12506                        // >0 priority for a protected actions, with ONE exception -- the setup
12507                        // wizard. The setup wizard, however, cannot be known until we're able to
12508                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12509                        // until all intent filters have been processed. Chicken, meet egg.
12510                        // Let the filter temporarily have a high priority and rectify the
12511                        // priorities after all system packages have been scanned.
12512                        mProtectedFilters.add(intent);
12513                        if (DEBUG_FILTERS) {
12514                            Slog.i(TAG, "Protected action; save for later;"
12515                                    + " package: " + applicationInfo.packageName
12516                                    + " activity: " + intent.activity.className
12517                                    + " origPrio: " + intent.getPriority());
12518                        }
12519                        return;
12520                    } else {
12521                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12522                            Slog.i(TAG, "No setup wizard;"
12523                                + " All protected intents capped to priority 0");
12524                        }
12525                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12526                            if (DEBUG_FILTERS) {
12527                                Slog.i(TAG, "Found setup wizard;"
12528                                    + " allow priority " + intent.getPriority() + ";"
12529                                    + " package: " + intent.activity.info.packageName
12530                                    + " activity: " + intent.activity.className
12531                                    + " priority: " + intent.getPriority());
12532                            }
12533                            // setup wizard gets whatever it wants
12534                            return;
12535                        }
12536                        if (DEBUG_FILTERS) {
12537                            Slog.i(TAG, "Protected action; cap priority to 0;"
12538                                    + " package: " + intent.activity.info.packageName
12539                                    + " activity: " + intent.activity.className
12540                                    + " origPrio: " + intent.getPriority());
12541                        }
12542                        intent.setPriority(0);
12543                        return;
12544                    }
12545                }
12546                // privileged apps on the system image get whatever priority they request
12547                return;
12548            }
12549
12550            // privileged app unbundled update ... try to find the same activity
12551            final PackageParser.Activity foundActivity =
12552                    findMatchingActivity(systemActivities, activityInfo);
12553            if (foundActivity == null) {
12554                // this is a new activity; it cannot obtain >0 priority
12555                if (DEBUG_FILTERS) {
12556                    Slog.i(TAG, "New activity; cap priority to 0;"
12557                            + " package: " + applicationInfo.packageName
12558                            + " activity: " + intent.activity.className
12559                            + " origPrio: " + intent.getPriority());
12560                }
12561                intent.setPriority(0);
12562                return;
12563            }
12564
12565            // found activity, now check for filter equivalence
12566
12567            // a shallow copy is enough; we modify the list, not its contents
12568            final List<ActivityIntentInfo> intentListCopy =
12569                    new ArrayList<>(foundActivity.intents);
12570            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12571
12572            // find matching action subsets
12573            final Iterator<String> actionsIterator = intent.actionsIterator();
12574            if (actionsIterator != null) {
12575                getIntentListSubset(
12576                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12577                if (intentListCopy.size() == 0) {
12578                    // no more intents to match; we're not equivalent
12579                    if (DEBUG_FILTERS) {
12580                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12581                                + " package: " + applicationInfo.packageName
12582                                + " activity: " + intent.activity.className
12583                                + " origPrio: " + intent.getPriority());
12584                    }
12585                    intent.setPriority(0);
12586                    return;
12587                }
12588            }
12589
12590            // find matching category subsets
12591            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12592            if (categoriesIterator != null) {
12593                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12594                        categoriesIterator);
12595                if (intentListCopy.size() == 0) {
12596                    // no more intents to match; we're not equivalent
12597                    if (DEBUG_FILTERS) {
12598                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12599                                + " package: " + applicationInfo.packageName
12600                                + " activity: " + intent.activity.className
12601                                + " origPrio: " + intent.getPriority());
12602                    }
12603                    intent.setPriority(0);
12604                    return;
12605                }
12606            }
12607
12608            // find matching schemes subsets
12609            final Iterator<String> schemesIterator = intent.schemesIterator();
12610            if (schemesIterator != null) {
12611                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12612                        schemesIterator);
12613                if (intentListCopy.size() == 0) {
12614                    // no more intents to match; we're not equivalent
12615                    if (DEBUG_FILTERS) {
12616                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12617                                + " package: " + applicationInfo.packageName
12618                                + " activity: " + intent.activity.className
12619                                + " origPrio: " + intent.getPriority());
12620                    }
12621                    intent.setPriority(0);
12622                    return;
12623                }
12624            }
12625
12626            // find matching authorities subsets
12627            final Iterator<IntentFilter.AuthorityEntry>
12628                    authoritiesIterator = intent.authoritiesIterator();
12629            if (authoritiesIterator != null) {
12630                getIntentListSubset(intentListCopy,
12631                        new AuthoritiesIterGenerator(),
12632                        authoritiesIterator);
12633                if (intentListCopy.size() == 0) {
12634                    // no more intents to match; we're not equivalent
12635                    if (DEBUG_FILTERS) {
12636                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12637                                + " package: " + applicationInfo.packageName
12638                                + " activity: " + intent.activity.className
12639                                + " origPrio: " + intent.getPriority());
12640                    }
12641                    intent.setPriority(0);
12642                    return;
12643                }
12644            }
12645
12646            // we found matching filter(s); app gets the max priority of all intents
12647            int cappedPriority = 0;
12648            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12649                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12650            }
12651            if (intent.getPriority() > cappedPriority) {
12652                if (DEBUG_FILTERS) {
12653                    Slog.i(TAG, "Found matching filter(s);"
12654                            + " cap priority to " + cappedPriority + ";"
12655                            + " package: " + applicationInfo.packageName
12656                            + " activity: " + intent.activity.className
12657                            + " origPrio: " + intent.getPriority());
12658                }
12659                intent.setPriority(cappedPriority);
12660                return;
12661            }
12662            // all this for nothing; the requested priority was <= what was on the system
12663        }
12664
12665        public final void addActivity(PackageParser.Activity a, String type) {
12666            mActivities.put(a.getComponentName(), a);
12667            if (DEBUG_SHOW_INFO)
12668                Log.v(
12669                TAG, "  " + type + " " +
12670                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12671            if (DEBUG_SHOW_INFO)
12672                Log.v(TAG, "    Class=" + a.info.name);
12673            final int NI = a.intents.size();
12674            for (int j=0; j<NI; j++) {
12675                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12676                if ("activity".equals(type)) {
12677                    final PackageSetting ps =
12678                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12679                    final List<PackageParser.Activity> systemActivities =
12680                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12681                    adjustPriority(systemActivities, intent);
12682                }
12683                if (DEBUG_SHOW_INFO) {
12684                    Log.v(TAG, "    IntentFilter:");
12685                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12686                }
12687                if (!intent.debugCheck()) {
12688                    Log.w(TAG, "==> For Activity " + a.info.name);
12689                }
12690                addFilter(intent);
12691            }
12692        }
12693
12694        public final void removeActivity(PackageParser.Activity a, String type) {
12695            mActivities.remove(a.getComponentName());
12696            if (DEBUG_SHOW_INFO) {
12697                Log.v(TAG, "  " + type + " "
12698                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12699                                : a.info.name) + ":");
12700                Log.v(TAG, "    Class=" + a.info.name);
12701            }
12702            final int NI = a.intents.size();
12703            for (int j=0; j<NI; j++) {
12704                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12705                if (DEBUG_SHOW_INFO) {
12706                    Log.v(TAG, "    IntentFilter:");
12707                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12708                }
12709                removeFilter(intent);
12710            }
12711        }
12712
12713        @Override
12714        protected boolean allowFilterResult(
12715                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12716            ActivityInfo filterAi = filter.activity.info;
12717            for (int i=dest.size()-1; i>=0; i--) {
12718                ActivityInfo destAi = dest.get(i).activityInfo;
12719                if (destAi.name == filterAi.name
12720                        && destAi.packageName == filterAi.packageName) {
12721                    return false;
12722                }
12723            }
12724            return true;
12725        }
12726
12727        @Override
12728        protected ActivityIntentInfo[] newArray(int size) {
12729            return new ActivityIntentInfo[size];
12730        }
12731
12732        @Override
12733        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12734            if (!sUserManager.exists(userId)) return true;
12735            PackageParser.Package p = filter.activity.owner;
12736            if (p != null) {
12737                PackageSetting ps = (PackageSetting)p.mExtras;
12738                if (ps != null) {
12739                    // System apps are never considered stopped for purposes of
12740                    // filtering, because there may be no way for the user to
12741                    // actually re-launch them.
12742                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12743                            && ps.getStopped(userId);
12744                }
12745            }
12746            return false;
12747        }
12748
12749        @Override
12750        protected boolean isPackageForFilter(String packageName,
12751                PackageParser.ActivityIntentInfo info) {
12752            return packageName.equals(info.activity.owner.packageName);
12753        }
12754
12755        @Override
12756        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12757                int match, int userId) {
12758            if (!sUserManager.exists(userId)) return null;
12759            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12760                return null;
12761            }
12762            final PackageParser.Activity activity = info.activity;
12763            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12764            if (ps == null) {
12765                return null;
12766            }
12767            final PackageUserState userState = ps.readUserState(userId);
12768            ActivityInfo ai =
12769                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12770            if (ai == null) {
12771                return null;
12772            }
12773            final boolean matchExplicitlyVisibleOnly =
12774                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12775            final boolean matchVisibleToInstantApp =
12776                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12777            final boolean componentVisible =
12778                    matchVisibleToInstantApp
12779                    && info.isVisibleToInstantApp()
12780                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12781            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12782            // throw out filters that aren't visible to ephemeral apps
12783            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12784                return null;
12785            }
12786            // throw out instant app filters if we're not explicitly requesting them
12787            if (!matchInstantApp && userState.instantApp) {
12788                return null;
12789            }
12790            // throw out instant app filters if updates are available; will trigger
12791            // instant app resolution
12792            if (userState.instantApp && ps.isUpdateAvailable()) {
12793                return null;
12794            }
12795            final ResolveInfo res = new ResolveInfo();
12796            res.activityInfo = ai;
12797            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12798                res.filter = info;
12799            }
12800            if (info != null) {
12801                res.handleAllWebDataURI = info.handleAllWebDataURI();
12802            }
12803            res.priority = info.getPriority();
12804            res.preferredOrder = activity.owner.mPreferredOrder;
12805            //System.out.println("Result: " + res.activityInfo.className +
12806            //                   " = " + res.priority);
12807            res.match = match;
12808            res.isDefault = info.hasDefault;
12809            res.labelRes = info.labelRes;
12810            res.nonLocalizedLabel = info.nonLocalizedLabel;
12811            if (userNeedsBadging(userId)) {
12812                res.noResourceId = true;
12813            } else {
12814                res.icon = info.icon;
12815            }
12816            res.iconResourceId = info.icon;
12817            res.system = res.activityInfo.applicationInfo.isSystemApp();
12818            res.isInstantAppAvailable = userState.instantApp;
12819            return res;
12820        }
12821
12822        @Override
12823        protected void sortResults(List<ResolveInfo> results) {
12824            Collections.sort(results, mResolvePrioritySorter);
12825        }
12826
12827        @Override
12828        protected void dumpFilter(PrintWriter out, String prefix,
12829                PackageParser.ActivityIntentInfo filter) {
12830            out.print(prefix); out.print(
12831                    Integer.toHexString(System.identityHashCode(filter.activity)));
12832                    out.print(' ');
12833                    filter.activity.printComponentShortName(out);
12834                    out.print(" filter ");
12835                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12836        }
12837
12838        @Override
12839        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12840            return filter.activity;
12841        }
12842
12843        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12844            PackageParser.Activity activity = (PackageParser.Activity)label;
12845            out.print(prefix); out.print(
12846                    Integer.toHexString(System.identityHashCode(activity)));
12847                    out.print(' ');
12848                    activity.printComponentShortName(out);
12849            if (count > 1) {
12850                out.print(" ("); out.print(count); out.print(" filters)");
12851            }
12852            out.println();
12853        }
12854
12855        // Keys are String (activity class name), values are Activity.
12856        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12857                = new ArrayMap<ComponentName, PackageParser.Activity>();
12858        private int mFlags;
12859    }
12860
12861    private final class ServiceIntentResolver
12862            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12863        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12864                boolean defaultOnly, int userId) {
12865            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12866            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12867        }
12868
12869        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12870                int userId) {
12871            if (!sUserManager.exists(userId)) return null;
12872            mFlags = flags;
12873            return super.queryIntent(intent, resolvedType,
12874                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12875                    userId);
12876        }
12877
12878        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12879                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12880            if (!sUserManager.exists(userId)) return null;
12881            if (packageServices == null) {
12882                return null;
12883            }
12884            mFlags = flags;
12885            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12886            final int N = packageServices.size();
12887            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12888                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12889
12890            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12891            for (int i = 0; i < N; ++i) {
12892                intentFilters = packageServices.get(i).intents;
12893                if (intentFilters != null && intentFilters.size() > 0) {
12894                    PackageParser.ServiceIntentInfo[] array =
12895                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12896                    intentFilters.toArray(array);
12897                    listCut.add(array);
12898                }
12899            }
12900            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12901        }
12902
12903        public final void addService(PackageParser.Service s) {
12904            mServices.put(s.getComponentName(), s);
12905            if (DEBUG_SHOW_INFO) {
12906                Log.v(TAG, "  "
12907                        + (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                if (!intent.debugCheck()) {
12920                    Log.w(TAG, "==> For Service " + s.info.name);
12921                }
12922                addFilter(intent);
12923            }
12924        }
12925
12926        public final void removeService(PackageParser.Service s) {
12927            mServices.remove(s.getComponentName());
12928            if (DEBUG_SHOW_INFO) {
12929                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12930                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12931                Log.v(TAG, "    Class=" + s.info.name);
12932            }
12933            final int NI = s.intents.size();
12934            int j;
12935            for (j=0; j<NI; j++) {
12936                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12937                if (DEBUG_SHOW_INFO) {
12938                    Log.v(TAG, "    IntentFilter:");
12939                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12940                }
12941                removeFilter(intent);
12942            }
12943        }
12944
12945        @Override
12946        protected boolean allowFilterResult(
12947                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12948            ServiceInfo filterSi = filter.service.info;
12949            for (int i=dest.size()-1; i>=0; i--) {
12950                ServiceInfo destAi = dest.get(i).serviceInfo;
12951                if (destAi.name == filterSi.name
12952                        && destAi.packageName == filterSi.packageName) {
12953                    return false;
12954                }
12955            }
12956            return true;
12957        }
12958
12959        @Override
12960        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12961            return new PackageParser.ServiceIntentInfo[size];
12962        }
12963
12964        @Override
12965        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12966            if (!sUserManager.exists(userId)) return true;
12967            PackageParser.Package p = filter.service.owner;
12968            if (p != null) {
12969                PackageSetting ps = (PackageSetting)p.mExtras;
12970                if (ps != null) {
12971                    // System apps are never considered stopped for purposes of
12972                    // filtering, because there may be no way for the user to
12973                    // actually re-launch them.
12974                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12975                            && ps.getStopped(userId);
12976                }
12977            }
12978            return false;
12979        }
12980
12981        @Override
12982        protected boolean isPackageForFilter(String packageName,
12983                PackageParser.ServiceIntentInfo info) {
12984            return packageName.equals(info.service.owner.packageName);
12985        }
12986
12987        @Override
12988        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12989                int match, int userId) {
12990            if (!sUserManager.exists(userId)) return null;
12991            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12992            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12993                return null;
12994            }
12995            final PackageParser.Service service = info.service;
12996            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12997            if (ps == null) {
12998                return null;
12999            }
13000            final PackageUserState userState = ps.readUserState(userId);
13001            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13002                    userState, userId);
13003            if (si == null) {
13004                return null;
13005            }
13006            final boolean matchVisibleToInstantApp =
13007                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13008            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13009            // throw out filters that aren't visible to ephemeral apps
13010            if (matchVisibleToInstantApp
13011                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13012                return null;
13013            }
13014            // throw out ephemeral filters if we're not explicitly requesting them
13015            if (!isInstantApp && userState.instantApp) {
13016                return null;
13017            }
13018            // throw out instant app filters if updates are available; will trigger
13019            // instant app resolution
13020            if (userState.instantApp && ps.isUpdateAvailable()) {
13021                return null;
13022            }
13023            final ResolveInfo res = new ResolveInfo();
13024            res.serviceInfo = si;
13025            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13026                res.filter = filter;
13027            }
13028            res.priority = info.getPriority();
13029            res.preferredOrder = service.owner.mPreferredOrder;
13030            res.match = match;
13031            res.isDefault = info.hasDefault;
13032            res.labelRes = info.labelRes;
13033            res.nonLocalizedLabel = info.nonLocalizedLabel;
13034            res.icon = info.icon;
13035            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13036            return res;
13037        }
13038
13039        @Override
13040        protected void sortResults(List<ResolveInfo> results) {
13041            Collections.sort(results, mResolvePrioritySorter);
13042        }
13043
13044        @Override
13045        protected void dumpFilter(PrintWriter out, String prefix,
13046                PackageParser.ServiceIntentInfo filter) {
13047            out.print(prefix); out.print(
13048                    Integer.toHexString(System.identityHashCode(filter.service)));
13049                    out.print(' ');
13050                    filter.service.printComponentShortName(out);
13051                    out.print(" filter ");
13052                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13053                    if (filter.service.info.permission != null) {
13054                        out.print(" permission "); out.println(filter.service.info.permission);
13055                    } else {
13056                        out.println();
13057                    }
13058        }
13059
13060        @Override
13061        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13062            return filter.service;
13063        }
13064
13065        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13066            PackageParser.Service service = (PackageParser.Service)label;
13067            out.print(prefix); out.print(
13068                    Integer.toHexString(System.identityHashCode(service)));
13069                    out.print(' ');
13070                    service.printComponentShortName(out);
13071            if (count > 1) {
13072                out.print(" ("); out.print(count); out.print(" filters)");
13073            }
13074            out.println();
13075        }
13076
13077//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13078//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13079//            final List<ResolveInfo> retList = Lists.newArrayList();
13080//            while (i.hasNext()) {
13081//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13082//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13083//                    retList.add(resolveInfo);
13084//                }
13085//            }
13086//            return retList;
13087//        }
13088
13089        // Keys are String (activity class name), values are Activity.
13090        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13091                = new ArrayMap<ComponentName, PackageParser.Service>();
13092        private int mFlags;
13093    }
13094
13095    private final class ProviderIntentResolver
13096            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13097        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13098                boolean defaultOnly, int userId) {
13099            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13100            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13101        }
13102
13103        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13104                int userId) {
13105            if (!sUserManager.exists(userId))
13106                return null;
13107            mFlags = flags;
13108            return super.queryIntent(intent, resolvedType,
13109                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13110                    userId);
13111        }
13112
13113        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13114                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13115            if (!sUserManager.exists(userId))
13116                return null;
13117            if (packageProviders == null) {
13118                return null;
13119            }
13120            mFlags = flags;
13121            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13122            final int N = packageProviders.size();
13123            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13124                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13125
13126            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13127            for (int i = 0; i < N; ++i) {
13128                intentFilters = packageProviders.get(i).intents;
13129                if (intentFilters != null && intentFilters.size() > 0) {
13130                    PackageParser.ProviderIntentInfo[] array =
13131                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13132                    intentFilters.toArray(array);
13133                    listCut.add(array);
13134                }
13135            }
13136            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13137        }
13138
13139        public final void addProvider(PackageParser.Provider p) {
13140            if (mProviders.containsKey(p.getComponentName())) {
13141                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13142                return;
13143            }
13144
13145            mProviders.put(p.getComponentName(), p);
13146            if (DEBUG_SHOW_INFO) {
13147                Log.v(TAG, "  "
13148                        + (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                if (!intent.debugCheck()) {
13161                    Log.w(TAG, "==> For Provider " + p.info.name);
13162                }
13163                addFilter(intent);
13164            }
13165        }
13166
13167        public final void removeProvider(PackageParser.Provider p) {
13168            mProviders.remove(p.getComponentName());
13169            if (DEBUG_SHOW_INFO) {
13170                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13171                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13172                Log.v(TAG, "    Class=" + p.info.name);
13173            }
13174            final int NI = p.intents.size();
13175            int j;
13176            for (j = 0; j < NI; j++) {
13177                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13178                if (DEBUG_SHOW_INFO) {
13179                    Log.v(TAG, "    IntentFilter:");
13180                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13181                }
13182                removeFilter(intent);
13183            }
13184        }
13185
13186        @Override
13187        protected boolean allowFilterResult(
13188                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13189            ProviderInfo filterPi = filter.provider.info;
13190            for (int i = dest.size() - 1; i >= 0; i--) {
13191                ProviderInfo destPi = dest.get(i).providerInfo;
13192                if (destPi.name == filterPi.name
13193                        && destPi.packageName == filterPi.packageName) {
13194                    return false;
13195                }
13196            }
13197            return true;
13198        }
13199
13200        @Override
13201        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13202            return new PackageParser.ProviderIntentInfo[size];
13203        }
13204
13205        @Override
13206        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13207            if (!sUserManager.exists(userId))
13208                return true;
13209            PackageParser.Package p = filter.provider.owner;
13210            if (p != null) {
13211                PackageSetting ps = (PackageSetting) p.mExtras;
13212                if (ps != null) {
13213                    // System apps are never considered stopped for purposes of
13214                    // filtering, because there may be no way for the user to
13215                    // actually re-launch them.
13216                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13217                            && ps.getStopped(userId);
13218                }
13219            }
13220            return false;
13221        }
13222
13223        @Override
13224        protected boolean isPackageForFilter(String packageName,
13225                PackageParser.ProviderIntentInfo info) {
13226            return packageName.equals(info.provider.owner.packageName);
13227        }
13228
13229        @Override
13230        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13231                int match, int userId) {
13232            if (!sUserManager.exists(userId))
13233                return null;
13234            final PackageParser.ProviderIntentInfo info = filter;
13235            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13236                return null;
13237            }
13238            final PackageParser.Provider provider = info.provider;
13239            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13240            if (ps == null) {
13241                return null;
13242            }
13243            final PackageUserState userState = ps.readUserState(userId);
13244            final boolean matchVisibleToInstantApp =
13245                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13246            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13247            // throw out filters that aren't visible to instant applications
13248            if (matchVisibleToInstantApp
13249                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13250                return null;
13251            }
13252            // throw out instant application filters if we're not explicitly requesting them
13253            if (!isInstantApp && userState.instantApp) {
13254                return null;
13255            }
13256            // throw out instant application filters if updates are available; will trigger
13257            // instant application resolution
13258            if (userState.instantApp && ps.isUpdateAvailable()) {
13259                return null;
13260            }
13261            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13262                    userState, userId);
13263            if (pi == null) {
13264                return null;
13265            }
13266            final ResolveInfo res = new ResolveInfo();
13267            res.providerInfo = pi;
13268            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13269                res.filter = filter;
13270            }
13271            res.priority = info.getPriority();
13272            res.preferredOrder = provider.owner.mPreferredOrder;
13273            res.match = match;
13274            res.isDefault = info.hasDefault;
13275            res.labelRes = info.labelRes;
13276            res.nonLocalizedLabel = info.nonLocalizedLabel;
13277            res.icon = info.icon;
13278            res.system = res.providerInfo.applicationInfo.isSystemApp();
13279            return res;
13280        }
13281
13282        @Override
13283        protected void sortResults(List<ResolveInfo> results) {
13284            Collections.sort(results, mResolvePrioritySorter);
13285        }
13286
13287        @Override
13288        protected void dumpFilter(PrintWriter out, String prefix,
13289                PackageParser.ProviderIntentInfo filter) {
13290            out.print(prefix);
13291            out.print(
13292                    Integer.toHexString(System.identityHashCode(filter.provider)));
13293            out.print(' ');
13294            filter.provider.printComponentShortName(out);
13295            out.print(" filter ");
13296            out.println(Integer.toHexString(System.identityHashCode(filter)));
13297        }
13298
13299        @Override
13300        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13301            return filter.provider;
13302        }
13303
13304        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13305            PackageParser.Provider provider = (PackageParser.Provider)label;
13306            out.print(prefix); out.print(
13307                    Integer.toHexString(System.identityHashCode(provider)));
13308                    out.print(' ');
13309                    provider.printComponentShortName(out);
13310            if (count > 1) {
13311                out.print(" ("); out.print(count); out.print(" filters)");
13312            }
13313            out.println();
13314        }
13315
13316        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13317                = new ArrayMap<ComponentName, PackageParser.Provider>();
13318        private int mFlags;
13319    }
13320
13321    static final class InstantAppIntentResolver
13322            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13323            AuxiliaryResolveInfo.AuxiliaryFilter> {
13324        /**
13325         * The result that has the highest defined order. Ordering applies on a
13326         * per-package basis. Mapping is from package name to Pair of order and
13327         * EphemeralResolveInfo.
13328         * <p>
13329         * NOTE: This is implemented as a field variable for convenience and efficiency.
13330         * By having a field variable, we're able to track filter ordering as soon as
13331         * a non-zero order is defined. Otherwise, multiple loops across the result set
13332         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13333         * this needs to be contained entirely within {@link #filterResults}.
13334         */
13335        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13336
13337        @Override
13338        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13339            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13340        }
13341
13342        @Override
13343        protected boolean isPackageForFilter(String packageName,
13344                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13345            return true;
13346        }
13347
13348        @Override
13349        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13350                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13351            if (!sUserManager.exists(userId)) {
13352                return null;
13353            }
13354            final String packageName = responseObj.resolveInfo.getPackageName();
13355            final Integer order = responseObj.getOrder();
13356            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13357                    mOrderResult.get(packageName);
13358            // ordering is enabled and this item's order isn't high enough
13359            if (lastOrderResult != null && lastOrderResult.first >= order) {
13360                return null;
13361            }
13362            final InstantAppResolveInfo res = responseObj.resolveInfo;
13363            if (order > 0) {
13364                // non-zero order, enable ordering
13365                mOrderResult.put(packageName, new Pair<>(order, res));
13366            }
13367            return responseObj;
13368        }
13369
13370        @Override
13371        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13372            // only do work if ordering is enabled [most of the time it won't be]
13373            if (mOrderResult.size() == 0) {
13374                return;
13375            }
13376            int resultSize = results.size();
13377            for (int i = 0; i < resultSize; i++) {
13378                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13379                final String packageName = info.getPackageName();
13380                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13381                if (savedInfo == null) {
13382                    // package doesn't having ordering
13383                    continue;
13384                }
13385                if (savedInfo.second == info) {
13386                    // circled back to the highest ordered item; remove from order list
13387                    mOrderResult.remove(packageName);
13388                    if (mOrderResult.size() == 0) {
13389                        // no more ordered items
13390                        break;
13391                    }
13392                    continue;
13393                }
13394                // item has a worse order, remove it from the result list
13395                results.remove(i);
13396                resultSize--;
13397                i--;
13398            }
13399        }
13400    }
13401
13402    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13403            new Comparator<ResolveInfo>() {
13404        public int compare(ResolveInfo r1, ResolveInfo r2) {
13405            int v1 = r1.priority;
13406            int v2 = r2.priority;
13407            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13408            if (v1 != v2) {
13409                return (v1 > v2) ? -1 : 1;
13410            }
13411            v1 = r1.preferredOrder;
13412            v2 = r2.preferredOrder;
13413            if (v1 != v2) {
13414                return (v1 > v2) ? -1 : 1;
13415            }
13416            if (r1.isDefault != r2.isDefault) {
13417                return r1.isDefault ? -1 : 1;
13418            }
13419            v1 = r1.match;
13420            v2 = r2.match;
13421            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13422            if (v1 != v2) {
13423                return (v1 > v2) ? -1 : 1;
13424            }
13425            if (r1.system != r2.system) {
13426                return r1.system ? -1 : 1;
13427            }
13428            if (r1.activityInfo != null) {
13429                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13430            }
13431            if (r1.serviceInfo != null) {
13432                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13433            }
13434            if (r1.providerInfo != null) {
13435                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13436            }
13437            return 0;
13438        }
13439    };
13440
13441    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13442            new Comparator<ProviderInfo>() {
13443        public int compare(ProviderInfo p1, ProviderInfo p2) {
13444            final int v1 = p1.initOrder;
13445            final int v2 = p2.initOrder;
13446            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13447        }
13448    };
13449
13450    @Override
13451    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13452            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13453            final int[] userIds, int[] instantUserIds) {
13454        mHandler.post(new Runnable() {
13455            @Override
13456            public void run() {
13457                try {
13458                    final IActivityManager am = ActivityManager.getService();
13459                    if (am == null) return;
13460                    final int[] resolvedUserIds;
13461                    if (userIds == null) {
13462                        resolvedUserIds = am.getRunningUserIds();
13463                    } else {
13464                        resolvedUserIds = userIds;
13465                    }
13466                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13467                            resolvedUserIds, false);
13468                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13469                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13470                                instantUserIds, true);
13471                    }
13472                } catch (RemoteException ex) {
13473                }
13474            }
13475        });
13476    }
13477
13478    @Override
13479    public void notifyPackageAdded(String packageName) {
13480        final PackageListObserver[] observers;
13481        synchronized (mPackages) {
13482            if (mPackageListObservers.size() == 0) {
13483                return;
13484            }
13485            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13486        }
13487        for (int i = observers.length - 1; i >= 0; --i) {
13488            observers[i].onPackageAdded(packageName);
13489        }
13490    }
13491
13492    @Override
13493    public void notifyPackageRemoved(String packageName) {
13494        final PackageListObserver[] observers;
13495        synchronized (mPackages) {
13496            if (mPackageListObservers.size() == 0) {
13497                return;
13498            }
13499            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13500        }
13501        for (int i = observers.length - 1; i >= 0; --i) {
13502            observers[i].onPackageRemoved(packageName);
13503        }
13504    }
13505
13506    /**
13507     * Sends a broadcast for the given action.
13508     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13509     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13510     * the system and applications allowed to see instant applications to receive package
13511     * lifecycle events for instant applications.
13512     */
13513    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13514            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13515            int[] userIds, boolean isInstantApp)
13516                    throws RemoteException {
13517        for (int id : userIds) {
13518            final Intent intent = new Intent(action,
13519                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13520            final String[] requiredPermissions =
13521                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13522            if (extras != null) {
13523                intent.putExtras(extras);
13524            }
13525            if (targetPkg != null) {
13526                intent.setPackage(targetPkg);
13527            }
13528            // Modify the UID when posting to other users
13529            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13530            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13531                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13532                intent.putExtra(Intent.EXTRA_UID, uid);
13533            }
13534            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13535            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13536            if (DEBUG_BROADCASTS) {
13537                RuntimeException here = new RuntimeException("here");
13538                here.fillInStackTrace();
13539                Slog.d(TAG, "Sending to user " + id + ": "
13540                        + intent.toShortString(false, true, false, false)
13541                        + " " + intent.getExtras(), here);
13542            }
13543            am.broadcastIntent(null, intent, null, finishedReceiver,
13544                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13545                    null, finishedReceiver != null, false, id);
13546        }
13547    }
13548
13549    /**
13550     * Check if the external storage media is available. This is true if there
13551     * is a mounted external storage medium or if the external storage is
13552     * emulated.
13553     */
13554    private boolean isExternalMediaAvailable() {
13555        return mMediaMounted || Environment.isExternalStorageEmulated();
13556    }
13557
13558    @Override
13559    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13560        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13561            return null;
13562        }
13563        if (!isExternalMediaAvailable()) {
13564                // If the external storage is no longer mounted at this point,
13565                // the caller may not have been able to delete all of this
13566                // packages files and can not delete any more.  Bail.
13567            return null;
13568        }
13569        synchronized (mPackages) {
13570            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13571            if (lastPackage != null) {
13572                pkgs.remove(lastPackage);
13573            }
13574            if (pkgs.size() > 0) {
13575                return pkgs.get(0);
13576            }
13577        }
13578        return null;
13579    }
13580
13581    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13582        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13583                userId, andCode ? 1 : 0, packageName);
13584        if (mSystemReady) {
13585            msg.sendToTarget();
13586        } else {
13587            if (mPostSystemReadyMessages == null) {
13588                mPostSystemReadyMessages = new ArrayList<>();
13589            }
13590            mPostSystemReadyMessages.add(msg);
13591        }
13592    }
13593
13594    void startCleaningPackages() {
13595        // reader
13596        if (!isExternalMediaAvailable()) {
13597            return;
13598        }
13599        synchronized (mPackages) {
13600            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13601                return;
13602            }
13603        }
13604        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13605        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13606        IActivityManager am = ActivityManager.getService();
13607        if (am != null) {
13608            int dcsUid = -1;
13609            synchronized (mPackages) {
13610                if (!mDefaultContainerWhitelisted) {
13611                    mDefaultContainerWhitelisted = true;
13612                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13613                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13614                }
13615            }
13616            try {
13617                if (dcsUid > 0) {
13618                    am.backgroundWhitelistUid(dcsUid);
13619                }
13620                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13621                        UserHandle.USER_SYSTEM);
13622            } catch (RemoteException e) {
13623            }
13624        }
13625    }
13626
13627    /**
13628     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13629     * it is acting on behalf on an enterprise or the user).
13630     *
13631     * Note that the ordering of the conditionals in this method is important. The checks we perform
13632     * are as follows, in this order:
13633     *
13634     * 1) If the install is being performed by a system app, we can trust the app to have set the
13635     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13636     *    what it is.
13637     * 2) If the install is being performed by a device or profile owner app, the install reason
13638     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13639     *    set the install reason correctly. If the app targets an older SDK version where install
13640     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13641     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13642     * 3) In all other cases, the install is being performed by a regular app that is neither part
13643     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13644     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13645     *    set to enterprise policy and if so, change it to unknown instead.
13646     */
13647    private int fixUpInstallReason(String installerPackageName, int installerUid,
13648            int installReason) {
13649        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13650                == PERMISSION_GRANTED) {
13651            // If the install is being performed by a system app, we trust that app to have set the
13652            // install reason correctly.
13653            return installReason;
13654        }
13655        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13656                UserHandle.getUserId(installerUid));
13657        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13658            // If the install is being performed by a device or profile owner, the install
13659            // reason should be enterprise policy.
13660            return PackageManager.INSTALL_REASON_POLICY;
13661        }
13662
13663
13664        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13665            // If the install is being performed by a regular app (i.e. neither system app nor
13666            // device or profile owner), we have no reason to believe that the app is acting on
13667            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13668            // change it to unknown instead.
13669            return PackageManager.INSTALL_REASON_UNKNOWN;
13670        }
13671
13672        // If the install is being performed by a regular app and the install reason was set to any
13673        // value but enterprise policy, leave the install reason unchanged.
13674        return installReason;
13675    }
13676
13677    /**
13678     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13679     * install commit.
13680     */
13681    void earlyBindToDefContainer() {
13682        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13683    }
13684
13685    void installStage(String packageName, File stagedDir,
13686            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13687            String installerPackageName, int installerUid, UserHandle user,
13688            PackageParser.SigningDetails signingDetails) {
13689        if (DEBUG_INSTANT) {
13690            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13691                Slog.d(TAG, "Ephemeral install of " + packageName);
13692            }
13693        }
13694        final VerificationInfo verificationInfo = new VerificationInfo(
13695                sessionParams.originatingUri, sessionParams.referrerUri,
13696                sessionParams.originatingUid, installerUid);
13697
13698        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13699
13700        final Message msg = mHandler.obtainMessage(INIT_COPY);
13701        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13702                sessionParams.installReason);
13703        final InstallParams params = new InstallParams(origin, null, observer,
13704                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13705                verificationInfo, user, sessionParams.abiOverride,
13706                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13707        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13708        msg.obj = params;
13709
13710        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13711                System.identityHashCode(msg.obj));
13712        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13713                System.identityHashCode(msg.obj));
13714
13715        mHandler.sendMessage(msg);
13716    }
13717
13718    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13719            int userId) {
13720        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13721        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13722        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13723        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13724        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13725                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13726
13727        // Send a session commit broadcast
13728        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13729        info.installReason = pkgSetting.getInstallReason(userId);
13730        info.appPackageName = packageName;
13731        sendSessionCommitBroadcast(info, userId);
13732    }
13733
13734    @Override
13735    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13736            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13737        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13738            return;
13739        }
13740        Bundle extras = new Bundle(1);
13741        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13742        final int uid = UserHandle.getUid(
13743                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13744        extras.putInt(Intent.EXTRA_UID, uid);
13745
13746        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13747                packageName, extras, 0, null, null, userIds, instantUserIds);
13748        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13749            mHandler.post(() -> {
13750                        for (int userId : userIds) {
13751                            sendBootCompletedBroadcastToSystemApp(
13752                                    packageName, includeStopped, userId);
13753                        }
13754                    }
13755            );
13756        }
13757    }
13758
13759    /**
13760     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13761     * automatically without needing an explicit launch.
13762     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13763     */
13764    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13765            int userId) {
13766        // If user is not running, the app didn't miss any broadcast
13767        if (!mUserManagerInternal.isUserRunning(userId)) {
13768            return;
13769        }
13770        final IActivityManager am = ActivityManager.getService();
13771        try {
13772            // Deliver LOCKED_BOOT_COMPLETED first
13773            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13774                    .setPackage(packageName);
13775            if (includeStopped) {
13776                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13777            }
13778            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13779            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13780                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13781
13782            // Deliver BOOT_COMPLETED only if user is unlocked
13783            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13784                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13785                if (includeStopped) {
13786                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13787                }
13788                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13789                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13790            }
13791        } catch (RemoteException e) {
13792            throw e.rethrowFromSystemServer();
13793        }
13794    }
13795
13796    @Override
13797    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13798            int userId) {
13799        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13800        PackageSetting pkgSetting;
13801        final int callingUid = Binder.getCallingUid();
13802        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13803                true /* requireFullPermission */, true /* checkShell */,
13804                "setApplicationHiddenSetting for user " + userId);
13805
13806        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13807            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13808            return false;
13809        }
13810
13811        long callingId = Binder.clearCallingIdentity();
13812        try {
13813            boolean sendAdded = false;
13814            boolean sendRemoved = false;
13815            // writer
13816            synchronized (mPackages) {
13817                pkgSetting = mSettings.mPackages.get(packageName);
13818                if (pkgSetting == null) {
13819                    return false;
13820                }
13821                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13822                    return false;
13823                }
13824                // Do not allow "android" is being disabled
13825                if ("android".equals(packageName)) {
13826                    Slog.w(TAG, "Cannot hide package: android");
13827                    return false;
13828                }
13829                // Cannot hide static shared libs as they are considered
13830                // a part of the using app (emulating static linking). Also
13831                // static libs are installed always on internal storage.
13832                PackageParser.Package pkg = mPackages.get(packageName);
13833                if (pkg != null && pkg.staticSharedLibName != null) {
13834                    Slog.w(TAG, "Cannot hide package: " + packageName
13835                            + " providing static shared library: "
13836                            + pkg.staticSharedLibName);
13837                    return false;
13838                }
13839                // Only allow protected packages to hide themselves.
13840                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13841                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13842                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13843                    return false;
13844                }
13845
13846                if (pkgSetting.getHidden(userId) != hidden) {
13847                    pkgSetting.setHidden(hidden, userId);
13848                    mSettings.writePackageRestrictionsLPr(userId);
13849                    if (hidden) {
13850                        sendRemoved = true;
13851                    } else {
13852                        sendAdded = true;
13853                    }
13854                }
13855            }
13856            if (sendAdded) {
13857                sendPackageAddedForUser(packageName, pkgSetting, userId);
13858                return true;
13859            }
13860            if (sendRemoved) {
13861                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13862                        "hiding pkg");
13863                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13864                return true;
13865            }
13866        } finally {
13867            Binder.restoreCallingIdentity(callingId);
13868        }
13869        return false;
13870    }
13871
13872    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13873            int userId) {
13874        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13875        info.removedPackage = packageName;
13876        info.installerPackageName = pkgSetting.installerPackageName;
13877        info.removedUsers = new int[] {userId};
13878        info.broadcastUsers = new int[] {userId};
13879        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13880        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13881    }
13882
13883    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13884            PersistableBundle launcherExtras) {
13885        if (pkgList.length > 0) {
13886            Bundle extras = new Bundle(1);
13887            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13888            if (launcherExtras != null) {
13889                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13890                        new Bundle(launcherExtras.deepCopy()));
13891            }
13892            sendPackageBroadcast(
13893                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13894                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13895                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13896                    new int[] {userId}, null);
13897        }
13898    }
13899
13900    /**
13901     * Returns true if application is not found or there was an error. Otherwise it returns
13902     * the hidden state of the package for the given user.
13903     */
13904    @Override
13905    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13906        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13907        final int callingUid = Binder.getCallingUid();
13908        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13909                true /* requireFullPermission */, false /* checkShell */,
13910                "getApplicationHidden for user " + userId);
13911        PackageSetting ps;
13912        long callingId = Binder.clearCallingIdentity();
13913        try {
13914            // writer
13915            synchronized (mPackages) {
13916                ps = mSettings.mPackages.get(packageName);
13917                if (ps == null) {
13918                    return true;
13919                }
13920                if (filterAppAccessLPr(ps, callingUid, userId)) {
13921                    return true;
13922                }
13923                return ps.getHidden(userId);
13924            }
13925        } finally {
13926            Binder.restoreCallingIdentity(callingId);
13927        }
13928    }
13929
13930    /**
13931     * @hide
13932     */
13933    @Override
13934    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13935            int installReason) {
13936        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13937                null);
13938        PackageSetting pkgSetting;
13939        final int callingUid = Binder.getCallingUid();
13940        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13941                true /* requireFullPermission */, true /* checkShell */,
13942                "installExistingPackage for user " + userId);
13943        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13944            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13945        }
13946
13947        long callingId = Binder.clearCallingIdentity();
13948        try {
13949            boolean installed = false;
13950            final boolean instantApp =
13951                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13952            final boolean fullApp =
13953                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13954
13955            // writer
13956            synchronized (mPackages) {
13957                pkgSetting = mSettings.mPackages.get(packageName);
13958                if (pkgSetting == null) {
13959                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13960                }
13961                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13962                    // only allow the existing package to be used if it's installed as a full
13963                    // application for at least one user
13964                    boolean installAllowed = false;
13965                    for (int checkUserId : sUserManager.getUserIds()) {
13966                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13967                        if (installAllowed) {
13968                            break;
13969                        }
13970                    }
13971                    if (!installAllowed) {
13972                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13973                    }
13974                }
13975                if (!pkgSetting.getInstalled(userId)) {
13976                    pkgSetting.setInstalled(true, userId);
13977                    pkgSetting.setHidden(false, userId);
13978                    pkgSetting.setInstallReason(installReason, userId);
13979                    mSettings.writePackageRestrictionsLPr(userId);
13980                    mSettings.writeKernelMappingLPr(pkgSetting);
13981                    installed = true;
13982                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13983                    // upgrade app from instant to full; we don't allow app downgrade
13984                    installed = true;
13985                }
13986                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13987            }
13988
13989            if (installed) {
13990                if (pkgSetting.pkg != null) {
13991                    synchronized (mInstallLock) {
13992                        // We don't need to freeze for a brand new install
13993                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13994                    }
13995                }
13996                sendPackageAddedForUser(packageName, pkgSetting, userId);
13997                synchronized (mPackages) {
13998                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13999                }
14000            }
14001        } finally {
14002            Binder.restoreCallingIdentity(callingId);
14003        }
14004
14005        return PackageManager.INSTALL_SUCCEEDED;
14006    }
14007
14008    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14009            boolean instantApp, boolean fullApp) {
14010        // no state specified; do nothing
14011        if (!instantApp && !fullApp) {
14012            return;
14013        }
14014        if (userId != UserHandle.USER_ALL) {
14015            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14016                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14017            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14018                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14019            }
14020        } else {
14021            for (int currentUserId : sUserManager.getUserIds()) {
14022                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14023                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14024                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14025                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14026                }
14027            }
14028        }
14029    }
14030
14031    boolean isUserRestricted(int userId, String restrictionKey) {
14032        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14033        if (restrictions.getBoolean(restrictionKey, false)) {
14034            Log.w(TAG, "User is restricted: " + restrictionKey);
14035            return true;
14036        }
14037        return false;
14038    }
14039
14040    @Override
14041    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14042            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14043            String callingPackage, int userId) {
14044        try {
14045            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14046        } catch (SecurityException e) {
14047            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14048                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14049                            + Manifest.permission.MANAGE_USERS);
14050        }
14051        final int callingUid = Binder.getCallingUid();
14052        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14053                true /* requireFullPermission */, true /* checkShell */,
14054                "setPackagesSuspended for user " + userId);
14055        if (callingUid != Process.ROOT_UID &&
14056                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
14057            throw new IllegalArgumentException("CallingPackage " + callingPackage + " does not"
14058                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14059        }
14060        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14061                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14062            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14063                    + userId + " has an active DO or PO");
14064        }
14065        if (ArrayUtils.isEmpty(packageNames)) {
14066            return packageNames;
14067        }
14068
14069        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14070        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14071        final long callingId = Binder.clearCallingIdentity();
14072        try {
14073            synchronized (mPackages) {
14074                for (int i = 0; i < packageNames.length; i++) {
14075                    final String packageName = packageNames[i];
14076                    if (callingPackage.equals(packageName)) {
14077                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14078                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14079                        unactionedPackages.add(packageName);
14080                        continue;
14081                    }
14082                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14083                    if (pkgSetting == null
14084                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14085                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14086                                + ". Skipping suspending/un-suspending.");
14087                        unactionedPackages.add(packageName);
14088                        continue;
14089                    }
14090                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14091                        unactionedPackages.add(packageName);
14092                        continue;
14093                    }
14094                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14095                            launcherExtras, userId);
14096                    changedPackagesList.add(packageName);
14097                }
14098            }
14099        } finally {
14100            Binder.restoreCallingIdentity(callingId);
14101        }
14102        if (!changedPackagesList.isEmpty()) {
14103            final String[] changedPackages = changedPackagesList.toArray(
14104                    new String[changedPackagesList.size()]);
14105            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14106            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14107            synchronized (mPackages) {
14108                scheduleWritePackageRestrictionsLocked(userId);
14109            }
14110        }
14111        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14112    }
14113
14114    @Override
14115    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14116        final int callingUid = Binder.getCallingUid();
14117        if (getPackageUid(packageName, 0, userId) != callingUid) {
14118            throw new SecurityException("Calling package " + packageName
14119                    + " does not belong to calling uid " + callingUid);
14120        }
14121        synchronized (mPackages) {
14122            final PackageSetting ps = mSettings.mPackages.get(packageName);
14123            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14124                throw new IllegalArgumentException("Unknown target package: " + packageName);
14125            }
14126            final PackageUserState packageUserState = ps.readUserState(userId);
14127            if (packageUserState.suspended) {
14128                return packageUserState.suspendedAppExtras;
14129            }
14130            return null;
14131        }
14132    }
14133
14134    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14135            PersistableBundle appExtras, int userId) {
14136        final String action;
14137        final Bundle intentExtras = new Bundle();
14138        if (suspended) {
14139            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14140            if (appExtras != null) {
14141                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14142                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14143            }
14144        } else {
14145            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14146        }
14147        mHandler.post(new Runnable() {
14148            @Override
14149            public void run() {
14150                try {
14151                    final IActivityManager am = ActivityManager.getService();
14152                    if (am == null) {
14153                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14154                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14155                        return;
14156                    }
14157                    final int[] targetUserIds = new int[] {userId};
14158                    for (String packageName : affectedPackages) {
14159                        doSendBroadcast(am, action, null, intentExtras,
14160                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14161                                targetUserIds, false);
14162                    }
14163                } catch (RemoteException ex) {
14164                    // Shouldn't happen as AMS is in the same process.
14165                }
14166            }
14167        });
14168    }
14169
14170    @Override
14171    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14172        final int callingUid = Binder.getCallingUid();
14173        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14174                true /* requireFullPermission */, false /* checkShell */,
14175                "isPackageSuspendedForUser for user " + userId);
14176        synchronized (mPackages) {
14177            final PackageSetting ps = mSettings.mPackages.get(packageName);
14178            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14179                throw new IllegalArgumentException("Unknown target package: " + packageName);
14180            }
14181            return ps.getSuspended(userId);
14182        }
14183    }
14184
14185    void onSuspendingPackageRemoved(String packageName, int removedForUser) {
14186        final int[] userIds = (removedForUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14187                : new int[] {removedForUser};
14188        for (int userId : userIds) {
14189            List<String> affectedPackages = new ArrayList<>();
14190            synchronized (mPackages) {
14191                for (PackageSetting ps : mSettings.mPackages.values()) {
14192                    final PackageUserState pus = ps.readUserState(userId);
14193                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14194                        ps.setSuspended(false, null, null, null, null, userId);
14195                        affectedPackages.add(ps.name);
14196                    }
14197                }
14198            }
14199            if (!affectedPackages.isEmpty()) {
14200                final String[] packageArray = affectedPackages.toArray(
14201                        new String[affectedPackages.size()]);
14202                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14203                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14204            }
14205        }
14206    }
14207
14208    @GuardedBy("mPackages")
14209    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14210        if (isPackageDeviceAdmin(packageName, userId)) {
14211            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14212                    + "\": has an active device admin");
14213            return false;
14214        }
14215
14216        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14217        if (packageName.equals(activeLauncherPackageName)) {
14218            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14219                    + "\": contains the active launcher");
14220            return false;
14221        }
14222
14223        if (packageName.equals(mRequiredInstallerPackage)) {
14224            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14225                    + "\": required for package installation");
14226            return false;
14227        }
14228
14229        if (packageName.equals(mRequiredUninstallerPackage)) {
14230            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14231                    + "\": required for package uninstallation");
14232            return false;
14233        }
14234
14235        if (packageName.equals(mRequiredVerifierPackage)) {
14236            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14237                    + "\": required for package verification");
14238            return false;
14239        }
14240
14241        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14242            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14243                    + "\": is the default dialer");
14244            return false;
14245        }
14246
14247        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14248            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14249                    + "\": protected package");
14250            return false;
14251        }
14252
14253        // Cannot suspend static shared libs as they are considered
14254        // a part of the using app (emulating static linking). Also
14255        // static libs are installed always on internal storage.
14256        PackageParser.Package pkg = mPackages.get(packageName);
14257        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14258            Slog.w(TAG, "Cannot suspend package: " + packageName
14259                    + " providing static shared library: "
14260                    + pkg.staticSharedLibName);
14261            return false;
14262        }
14263
14264        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14265            Slog.w(TAG, "Cannot suspend package: " + packageName);
14266            return false;
14267        }
14268
14269        return true;
14270    }
14271
14272    private String getActiveLauncherPackageName(int userId) {
14273        Intent intent = new Intent(Intent.ACTION_MAIN);
14274        intent.addCategory(Intent.CATEGORY_HOME);
14275        ResolveInfo resolveInfo = resolveIntent(
14276                intent,
14277                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14278                PackageManager.MATCH_DEFAULT_ONLY,
14279                userId);
14280
14281        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14282    }
14283
14284    private String getDefaultDialerPackageName(int userId) {
14285        synchronized (mPackages) {
14286            return mSettings.getDefaultDialerPackageNameLPw(userId);
14287        }
14288    }
14289
14290    @Override
14291    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14292        mContext.enforceCallingOrSelfPermission(
14293                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14294                "Only package verification agents can verify applications");
14295
14296        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14297        final PackageVerificationResponse response = new PackageVerificationResponse(
14298                verificationCode, Binder.getCallingUid());
14299        msg.arg1 = id;
14300        msg.obj = response;
14301        mHandler.sendMessage(msg);
14302    }
14303
14304    @Override
14305    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14306            long millisecondsToDelay) {
14307        mContext.enforceCallingOrSelfPermission(
14308                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14309                "Only package verification agents can extend verification timeouts");
14310
14311        final PackageVerificationState state = mPendingVerification.get(id);
14312        final PackageVerificationResponse response = new PackageVerificationResponse(
14313                verificationCodeAtTimeout, Binder.getCallingUid());
14314
14315        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14316            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14317        }
14318        if (millisecondsToDelay < 0) {
14319            millisecondsToDelay = 0;
14320        }
14321        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14322                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14323            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14324        }
14325
14326        if ((state != null) && !state.timeoutExtended()) {
14327            state.extendTimeout();
14328
14329            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14330            msg.arg1 = id;
14331            msg.obj = response;
14332            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14333        }
14334    }
14335
14336    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14337            int verificationCode, UserHandle user) {
14338        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14339        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14340        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14341        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14342        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14343
14344        mContext.sendBroadcastAsUser(intent, user,
14345                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14346    }
14347
14348    private ComponentName matchComponentForVerifier(String packageName,
14349            List<ResolveInfo> receivers) {
14350        ActivityInfo targetReceiver = null;
14351
14352        final int NR = receivers.size();
14353        for (int i = 0; i < NR; i++) {
14354            final ResolveInfo info = receivers.get(i);
14355            if (info.activityInfo == null) {
14356                continue;
14357            }
14358
14359            if (packageName.equals(info.activityInfo.packageName)) {
14360                targetReceiver = info.activityInfo;
14361                break;
14362            }
14363        }
14364
14365        if (targetReceiver == null) {
14366            return null;
14367        }
14368
14369        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14370    }
14371
14372    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14373            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14374        if (pkgInfo.verifiers.length == 0) {
14375            return null;
14376        }
14377
14378        final int N = pkgInfo.verifiers.length;
14379        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14380        for (int i = 0; i < N; i++) {
14381            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14382
14383            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14384                    receivers);
14385            if (comp == null) {
14386                continue;
14387            }
14388
14389            final int verifierUid = getUidForVerifier(verifierInfo);
14390            if (verifierUid == -1) {
14391                continue;
14392            }
14393
14394            if (DEBUG_VERIFY) {
14395                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14396                        + " with the correct signature");
14397            }
14398            sufficientVerifiers.add(comp);
14399            verificationState.addSufficientVerifier(verifierUid);
14400        }
14401
14402        return sufficientVerifiers;
14403    }
14404
14405    private int getUidForVerifier(VerifierInfo verifierInfo) {
14406        synchronized (mPackages) {
14407            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14408            if (pkg == null) {
14409                return -1;
14410            } else if (pkg.mSigningDetails.signatures.length != 1) {
14411                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14412                        + " has more than one signature; ignoring");
14413                return -1;
14414            }
14415
14416            /*
14417             * If the public key of the package's signature does not match
14418             * our expected public key, then this is a different package and
14419             * we should skip.
14420             */
14421
14422            final byte[] expectedPublicKey;
14423            try {
14424                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14425                final PublicKey publicKey = verifierSig.getPublicKey();
14426                expectedPublicKey = publicKey.getEncoded();
14427            } catch (CertificateException e) {
14428                return -1;
14429            }
14430
14431            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14432
14433            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14434                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14435                        + " does not have the expected public key; ignoring");
14436                return -1;
14437            }
14438
14439            return pkg.applicationInfo.uid;
14440        }
14441    }
14442
14443    @Override
14444    public void finishPackageInstall(int token, boolean didLaunch) {
14445        enforceSystemOrRoot("Only the system is allowed to finish installs");
14446
14447        if (DEBUG_INSTALL) {
14448            Slog.v(TAG, "BM finishing package install for " + token);
14449        }
14450        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14451
14452        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14453        mHandler.sendMessage(msg);
14454    }
14455
14456    /**
14457     * Get the verification agent timeout.  Used for both the APK verifier and the
14458     * intent filter verifier.
14459     *
14460     * @return verification timeout in milliseconds
14461     */
14462    private long getVerificationTimeout() {
14463        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14464                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14465                DEFAULT_VERIFICATION_TIMEOUT);
14466    }
14467
14468    /**
14469     * Get the default verification agent response code.
14470     *
14471     * @return default verification response code
14472     */
14473    private int getDefaultVerificationResponse(UserHandle user) {
14474        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14475            return PackageManager.VERIFICATION_REJECT;
14476        }
14477        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14478                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14479                DEFAULT_VERIFICATION_RESPONSE);
14480    }
14481
14482    /**
14483     * Check whether or not package verification has been enabled.
14484     *
14485     * @return true if verification should be performed
14486     */
14487    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14488        if (!DEFAULT_VERIFY_ENABLE) {
14489            return false;
14490        }
14491
14492        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14493
14494        // Check if installing from ADB
14495        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14496            // Do not run verification in a test harness environment
14497            if (ActivityManager.isRunningInTestHarness()) {
14498                return false;
14499            }
14500            if (ensureVerifyAppsEnabled) {
14501                return true;
14502            }
14503            // Check if the developer does not want package verification for ADB installs
14504            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14505                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14506                return false;
14507            }
14508        } else {
14509            // only when not installed from ADB, skip verification for instant apps when
14510            // the installer and verifier are the same.
14511            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14512                if (mInstantAppInstallerActivity != null
14513                        && mInstantAppInstallerActivity.packageName.equals(
14514                                mRequiredVerifierPackage)) {
14515                    try {
14516                        mContext.getSystemService(AppOpsManager.class)
14517                                .checkPackage(installerUid, mRequiredVerifierPackage);
14518                        if (DEBUG_VERIFY) {
14519                            Slog.i(TAG, "disable verification for instant app");
14520                        }
14521                        return false;
14522                    } catch (SecurityException ignore) { }
14523                }
14524            }
14525        }
14526
14527        if (ensureVerifyAppsEnabled) {
14528            return true;
14529        }
14530
14531        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14532                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14533    }
14534
14535    @Override
14536    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14537            throws RemoteException {
14538        mContext.enforceCallingOrSelfPermission(
14539                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14540                "Only intentfilter verification agents can verify applications");
14541
14542        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14543        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14544                Binder.getCallingUid(), verificationCode, failedDomains);
14545        msg.arg1 = id;
14546        msg.obj = response;
14547        mHandler.sendMessage(msg);
14548    }
14549
14550    @Override
14551    public int getIntentVerificationStatus(String packageName, int userId) {
14552        final int callingUid = Binder.getCallingUid();
14553        if (UserHandle.getUserId(callingUid) != userId) {
14554            mContext.enforceCallingOrSelfPermission(
14555                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14556                    "getIntentVerificationStatus" + userId);
14557        }
14558        if (getInstantAppPackageName(callingUid) != null) {
14559            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14560        }
14561        synchronized (mPackages) {
14562            final PackageSetting ps = mSettings.mPackages.get(packageName);
14563            if (ps == null
14564                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14565                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14566            }
14567            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14568        }
14569    }
14570
14571    @Override
14572    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14573        mContext.enforceCallingOrSelfPermission(
14574                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14575
14576        boolean result = false;
14577        synchronized (mPackages) {
14578            final PackageSetting ps = mSettings.mPackages.get(packageName);
14579            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14580                return false;
14581            }
14582            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14583        }
14584        if (result) {
14585            scheduleWritePackageRestrictionsLocked(userId);
14586        }
14587        return result;
14588    }
14589
14590    @Override
14591    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14592            String packageName) {
14593        final int callingUid = Binder.getCallingUid();
14594        if (getInstantAppPackageName(callingUid) != null) {
14595            return ParceledListSlice.emptyList();
14596        }
14597        synchronized (mPackages) {
14598            final PackageSetting ps = mSettings.mPackages.get(packageName);
14599            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14600                return ParceledListSlice.emptyList();
14601            }
14602            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14603        }
14604    }
14605
14606    @Override
14607    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14608        if (TextUtils.isEmpty(packageName)) {
14609            return ParceledListSlice.emptyList();
14610        }
14611        final int callingUid = Binder.getCallingUid();
14612        final int callingUserId = UserHandle.getUserId(callingUid);
14613        synchronized (mPackages) {
14614            PackageParser.Package pkg = mPackages.get(packageName);
14615            if (pkg == null || pkg.activities == null) {
14616                return ParceledListSlice.emptyList();
14617            }
14618            if (pkg.mExtras == null) {
14619                return ParceledListSlice.emptyList();
14620            }
14621            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14622            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14623                return ParceledListSlice.emptyList();
14624            }
14625            final int count = pkg.activities.size();
14626            ArrayList<IntentFilter> result = new ArrayList<>();
14627            for (int n=0; n<count; n++) {
14628                PackageParser.Activity activity = pkg.activities.get(n);
14629                if (activity.intents != null && activity.intents.size() > 0) {
14630                    result.addAll(activity.intents);
14631                }
14632            }
14633            return new ParceledListSlice<>(result);
14634        }
14635    }
14636
14637    @Override
14638    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14639        mContext.enforceCallingOrSelfPermission(
14640                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14641        if (UserHandle.getCallingUserId() != userId) {
14642            mContext.enforceCallingOrSelfPermission(
14643                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14644        }
14645
14646        synchronized (mPackages) {
14647            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14648            if (packageName != null) {
14649                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14650                        packageName, userId);
14651            }
14652            return result;
14653        }
14654    }
14655
14656    @Override
14657    public String getDefaultBrowserPackageName(int userId) {
14658        if (UserHandle.getCallingUserId() != userId) {
14659            mContext.enforceCallingOrSelfPermission(
14660                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14661        }
14662        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14663            return null;
14664        }
14665        synchronized (mPackages) {
14666            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14667        }
14668    }
14669
14670    /**
14671     * Get the "allow unknown sources" setting.
14672     *
14673     * @return the current "allow unknown sources" setting
14674     */
14675    private int getUnknownSourcesSettings() {
14676        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14677                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14678                -1);
14679    }
14680
14681    @Override
14682    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14683        final int callingUid = Binder.getCallingUid();
14684        if (getInstantAppPackageName(callingUid) != null) {
14685            return;
14686        }
14687        // writer
14688        synchronized (mPackages) {
14689            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14690            if (targetPackageSetting == null
14691                    || filterAppAccessLPr(
14692                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14693                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14694            }
14695
14696            PackageSetting installerPackageSetting;
14697            if (installerPackageName != null) {
14698                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14699                if (installerPackageSetting == null) {
14700                    throw new IllegalArgumentException("Unknown installer package: "
14701                            + installerPackageName);
14702                }
14703            } else {
14704                installerPackageSetting = null;
14705            }
14706
14707            Signature[] callerSignature;
14708            Object obj = mSettings.getUserIdLPr(callingUid);
14709            if (obj != null) {
14710                if (obj instanceof SharedUserSetting) {
14711                    callerSignature =
14712                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14713                } else if (obj instanceof PackageSetting) {
14714                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14715                } else {
14716                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14717                }
14718            } else {
14719                throw new SecurityException("Unknown calling UID: " + callingUid);
14720            }
14721
14722            // Verify: can't set installerPackageName to a package that is
14723            // not signed with the same cert as the caller.
14724            if (installerPackageSetting != null) {
14725                if (compareSignatures(callerSignature,
14726                        installerPackageSetting.signatures.mSigningDetails.signatures)
14727                        != PackageManager.SIGNATURE_MATCH) {
14728                    throw new SecurityException(
14729                            "Caller does not have same cert as new installer package "
14730                            + installerPackageName);
14731                }
14732            }
14733
14734            // Verify: if target already has an installer package, it must
14735            // be signed with the same cert as the caller.
14736            if (targetPackageSetting.installerPackageName != null) {
14737                PackageSetting setting = mSettings.mPackages.get(
14738                        targetPackageSetting.installerPackageName);
14739                // If the currently set package isn't valid, then it's always
14740                // okay to change it.
14741                if (setting != null) {
14742                    if (compareSignatures(callerSignature,
14743                            setting.signatures.mSigningDetails.signatures)
14744                            != PackageManager.SIGNATURE_MATCH) {
14745                        throw new SecurityException(
14746                                "Caller does not have same cert as old installer package "
14747                                + targetPackageSetting.installerPackageName);
14748                    }
14749                }
14750            }
14751
14752            // Okay!
14753            targetPackageSetting.installerPackageName = installerPackageName;
14754            if (installerPackageName != null) {
14755                mSettings.mInstallerPackages.add(installerPackageName);
14756            }
14757            scheduleWriteSettingsLocked();
14758        }
14759    }
14760
14761    @Override
14762    public void setApplicationCategoryHint(String packageName, int categoryHint,
14763            String callerPackageName) {
14764        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14765            throw new SecurityException("Instant applications don't have access to this method");
14766        }
14767        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14768                callerPackageName);
14769        synchronized (mPackages) {
14770            PackageSetting ps = mSettings.mPackages.get(packageName);
14771            if (ps == null) {
14772                throw new IllegalArgumentException("Unknown target package " + packageName);
14773            }
14774            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14775                throw new IllegalArgumentException("Unknown target package " + packageName);
14776            }
14777            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14778                throw new IllegalArgumentException("Calling package " + callerPackageName
14779                        + " is not installer for " + packageName);
14780            }
14781
14782            if (ps.categoryHint != categoryHint) {
14783                ps.categoryHint = categoryHint;
14784                scheduleWriteSettingsLocked();
14785            }
14786        }
14787    }
14788
14789    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14790        // Queue up an async operation since the package installation may take a little while.
14791        mHandler.post(new Runnable() {
14792            public void run() {
14793                mHandler.removeCallbacks(this);
14794                 // Result object to be returned
14795                PackageInstalledInfo res = new PackageInstalledInfo();
14796                res.setReturnCode(currentStatus);
14797                res.uid = -1;
14798                res.pkg = null;
14799                res.removedInfo = null;
14800                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14801                    args.doPreInstall(res.returnCode);
14802                    synchronized (mInstallLock) {
14803                        installPackageTracedLI(args, res);
14804                    }
14805                    args.doPostInstall(res.returnCode, res.uid);
14806                }
14807
14808                // A restore should be performed at this point if (a) the install
14809                // succeeded, (b) the operation is not an update, and (c) the new
14810                // package has not opted out of backup participation.
14811                final boolean update = res.removedInfo != null
14812                        && res.removedInfo.removedPackage != null;
14813                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14814                boolean doRestore = !update
14815                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14816
14817                // Set up the post-install work request bookkeeping.  This will be used
14818                // and cleaned up by the post-install event handling regardless of whether
14819                // there's a restore pass performed.  Token values are >= 1.
14820                int token;
14821                if (mNextInstallToken < 0) mNextInstallToken = 1;
14822                token = mNextInstallToken++;
14823
14824                PostInstallData data = new PostInstallData(args, res);
14825                mRunningInstalls.put(token, data);
14826                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14827
14828                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14829                    // Pass responsibility to the Backup Manager.  It will perform a
14830                    // restore if appropriate, then pass responsibility back to the
14831                    // Package Manager to run the post-install observer callbacks
14832                    // and broadcasts.
14833                    IBackupManager bm = IBackupManager.Stub.asInterface(
14834                            ServiceManager.getService(Context.BACKUP_SERVICE));
14835                    if (bm != null) {
14836                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14837                                + " to BM for possible restore");
14838                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14839                        try {
14840                            // TODO: http://b/22388012
14841                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14842                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14843                            } else {
14844                                doRestore = false;
14845                            }
14846                        } catch (RemoteException e) {
14847                            // can't happen; the backup manager is local
14848                        } catch (Exception e) {
14849                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14850                            doRestore = false;
14851                        }
14852                    } else {
14853                        Slog.e(TAG, "Backup Manager not found!");
14854                        doRestore = false;
14855                    }
14856                }
14857
14858                if (!doRestore) {
14859                    // No restore possible, or the Backup Manager was mysteriously not
14860                    // available -- just fire the post-install work request directly.
14861                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14862
14863                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14864
14865                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14866                    mHandler.sendMessage(msg);
14867                }
14868            }
14869        });
14870    }
14871
14872    /**
14873     * Callback from PackageSettings whenever an app is first transitioned out of the
14874     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14875     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14876     * here whether the app is the target of an ongoing install, and only send the
14877     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14878     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14879     * handling.
14880     */
14881    void notifyFirstLaunch(final String packageName, final String installerPackage,
14882            final int userId) {
14883        // Serialize this with the rest of the install-process message chain.  In the
14884        // restore-at-install case, this Runnable will necessarily run before the
14885        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14886        // are coherent.  In the non-restore case, the app has already completed install
14887        // and been launched through some other means, so it is not in a problematic
14888        // state for observers to see the FIRST_LAUNCH signal.
14889        mHandler.post(new Runnable() {
14890            @Override
14891            public void run() {
14892                for (int i = 0; i < mRunningInstalls.size(); i++) {
14893                    final PostInstallData data = mRunningInstalls.valueAt(i);
14894                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14895                        continue;
14896                    }
14897                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14898                        // right package; but is it for the right user?
14899                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14900                            if (userId == data.res.newUsers[uIndex]) {
14901                                if (DEBUG_BACKUP) {
14902                                    Slog.i(TAG, "Package " + packageName
14903                                            + " being restored so deferring FIRST_LAUNCH");
14904                                }
14905                                return;
14906                            }
14907                        }
14908                    }
14909                }
14910                // didn't find it, so not being restored
14911                if (DEBUG_BACKUP) {
14912                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14913                }
14914                final boolean isInstantApp = isInstantApp(packageName, userId);
14915                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14916                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14917                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14918            }
14919        });
14920    }
14921
14922    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14923            int[] userIds, int[] instantUserIds) {
14924        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14925                installerPkg, null, userIds, instantUserIds);
14926    }
14927
14928    private abstract class HandlerParams {
14929        private static final int MAX_RETRIES = 4;
14930
14931        /**
14932         * Number of times startCopy() has been attempted and had a non-fatal
14933         * error.
14934         */
14935        private int mRetries = 0;
14936
14937        /** User handle for the user requesting the information or installation. */
14938        private final UserHandle mUser;
14939        String traceMethod;
14940        int traceCookie;
14941
14942        HandlerParams(UserHandle user) {
14943            mUser = user;
14944        }
14945
14946        UserHandle getUser() {
14947            return mUser;
14948        }
14949
14950        HandlerParams setTraceMethod(String traceMethod) {
14951            this.traceMethod = traceMethod;
14952            return this;
14953        }
14954
14955        HandlerParams setTraceCookie(int traceCookie) {
14956            this.traceCookie = traceCookie;
14957            return this;
14958        }
14959
14960        final boolean startCopy() {
14961            boolean res;
14962            try {
14963                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14964
14965                if (++mRetries > MAX_RETRIES) {
14966                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14967                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14968                    handleServiceError();
14969                    return false;
14970                } else {
14971                    handleStartCopy();
14972                    res = true;
14973                }
14974            } catch (RemoteException e) {
14975                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14976                mHandler.sendEmptyMessage(MCS_RECONNECT);
14977                res = false;
14978            }
14979            handleReturnCode();
14980            return res;
14981        }
14982
14983        final void serviceError() {
14984            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14985            handleServiceError();
14986            handleReturnCode();
14987        }
14988
14989        abstract void handleStartCopy() throws RemoteException;
14990        abstract void handleServiceError();
14991        abstract void handleReturnCode();
14992    }
14993
14994    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14995        for (File path : paths) {
14996            try {
14997                mcs.clearDirectory(path.getAbsolutePath());
14998            } catch (RemoteException e) {
14999            }
15000        }
15001    }
15002
15003    static class OriginInfo {
15004        /**
15005         * Location where install is coming from, before it has been
15006         * copied/renamed into place. This could be a single monolithic APK
15007         * file, or a cluster directory. This location may be untrusted.
15008         */
15009        final File file;
15010
15011        /**
15012         * Flag indicating that {@link #file} or {@link #cid} has already been
15013         * staged, meaning downstream users don't need to defensively copy the
15014         * contents.
15015         */
15016        final boolean staged;
15017
15018        /**
15019         * Flag indicating that {@link #file} or {@link #cid} is an already
15020         * installed app that is being moved.
15021         */
15022        final boolean existing;
15023
15024        final String resolvedPath;
15025        final File resolvedFile;
15026
15027        static OriginInfo fromNothing() {
15028            return new OriginInfo(null, false, false);
15029        }
15030
15031        static OriginInfo fromUntrustedFile(File file) {
15032            return new OriginInfo(file, false, false);
15033        }
15034
15035        static OriginInfo fromExistingFile(File file) {
15036            return new OriginInfo(file, false, true);
15037        }
15038
15039        static OriginInfo fromStagedFile(File file) {
15040            return new OriginInfo(file, true, false);
15041        }
15042
15043        private OriginInfo(File file, boolean staged, boolean existing) {
15044            this.file = file;
15045            this.staged = staged;
15046            this.existing = existing;
15047
15048            if (file != null) {
15049                resolvedPath = file.getAbsolutePath();
15050                resolvedFile = file;
15051            } else {
15052                resolvedPath = null;
15053                resolvedFile = null;
15054            }
15055        }
15056    }
15057
15058    static class MoveInfo {
15059        final int moveId;
15060        final String fromUuid;
15061        final String toUuid;
15062        final String packageName;
15063        final String dataAppName;
15064        final int appId;
15065        final String seinfo;
15066        final int targetSdkVersion;
15067
15068        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15069                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15070            this.moveId = moveId;
15071            this.fromUuid = fromUuid;
15072            this.toUuid = toUuid;
15073            this.packageName = packageName;
15074            this.dataAppName = dataAppName;
15075            this.appId = appId;
15076            this.seinfo = seinfo;
15077            this.targetSdkVersion = targetSdkVersion;
15078        }
15079    }
15080
15081    static class VerificationInfo {
15082        /** A constant used to indicate that a uid value is not present. */
15083        public static final int NO_UID = -1;
15084
15085        /** URI referencing where the package was downloaded from. */
15086        final Uri originatingUri;
15087
15088        /** HTTP referrer URI associated with the originatingURI. */
15089        final Uri referrer;
15090
15091        /** UID of the application that the install request originated from. */
15092        final int originatingUid;
15093
15094        /** UID of application requesting the install */
15095        final int installerUid;
15096
15097        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15098            this.originatingUri = originatingUri;
15099            this.referrer = referrer;
15100            this.originatingUid = originatingUid;
15101            this.installerUid = installerUid;
15102        }
15103    }
15104
15105    class InstallParams extends HandlerParams {
15106        final OriginInfo origin;
15107        final MoveInfo move;
15108        final IPackageInstallObserver2 observer;
15109        int installFlags;
15110        final String installerPackageName;
15111        final String volumeUuid;
15112        private InstallArgs mArgs;
15113        private int mRet;
15114        final String packageAbiOverride;
15115        final String[] grantedRuntimePermissions;
15116        final VerificationInfo verificationInfo;
15117        final PackageParser.SigningDetails signingDetails;
15118        final int installReason;
15119
15120        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15121                int installFlags, String installerPackageName, String volumeUuid,
15122                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15123                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15124            super(user);
15125            this.origin = origin;
15126            this.move = move;
15127            this.observer = observer;
15128            this.installFlags = installFlags;
15129            this.installerPackageName = installerPackageName;
15130            this.volumeUuid = volumeUuid;
15131            this.verificationInfo = verificationInfo;
15132            this.packageAbiOverride = packageAbiOverride;
15133            this.grantedRuntimePermissions = grantedPermissions;
15134            this.signingDetails = signingDetails;
15135            this.installReason = installReason;
15136        }
15137
15138        @Override
15139        public String toString() {
15140            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15141                    + " file=" + origin.file + "}";
15142        }
15143
15144        private int installLocationPolicy(PackageInfoLite pkgLite) {
15145            String packageName = pkgLite.packageName;
15146            int installLocation = pkgLite.installLocation;
15147            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15148            // reader
15149            synchronized (mPackages) {
15150                // Currently installed package which the new package is attempting to replace or
15151                // null if no such package is installed.
15152                PackageParser.Package installedPkg = mPackages.get(packageName);
15153                // Package which currently owns the data which the new package will own if installed.
15154                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15155                // will be null whereas dataOwnerPkg will contain information about the package
15156                // which was uninstalled while keeping its data.
15157                PackageParser.Package dataOwnerPkg = installedPkg;
15158                if (dataOwnerPkg  == null) {
15159                    PackageSetting ps = mSettings.mPackages.get(packageName);
15160                    if (ps != null) {
15161                        dataOwnerPkg = ps.pkg;
15162                    }
15163                }
15164
15165                if (dataOwnerPkg != null) {
15166                    // If installed, the package will get access to data left on the device by its
15167                    // predecessor. As a security measure, this is permited only if this is not a
15168                    // version downgrade or if the predecessor package is marked as debuggable and
15169                    // a downgrade is explicitly requested.
15170                    //
15171                    // On debuggable platform builds, downgrades are permitted even for
15172                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15173                    // not offer security guarantees and thus it's OK to disable some security
15174                    // mechanisms to make debugging/testing easier on those builds. However, even on
15175                    // debuggable builds downgrades of packages are permitted only if requested via
15176                    // installFlags. This is because we aim to keep the behavior of debuggable
15177                    // platform builds as close as possible to the behavior of non-debuggable
15178                    // platform builds.
15179                    final boolean downgradeRequested =
15180                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15181                    final boolean packageDebuggable =
15182                                (dataOwnerPkg.applicationInfo.flags
15183                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15184                    final boolean downgradePermitted =
15185                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15186                    if (!downgradePermitted) {
15187                        try {
15188                            checkDowngrade(dataOwnerPkg, pkgLite);
15189                        } catch (PackageManagerException e) {
15190                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15191                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15192                        }
15193                    }
15194                }
15195
15196                if (installedPkg != null) {
15197                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15198                        // Check for updated system application.
15199                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15200                            if (onSd) {
15201                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15202                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15203                            }
15204                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15205                        } else {
15206                            if (onSd) {
15207                                // Install flag overrides everything.
15208                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15209                            }
15210                            // If current upgrade specifies particular preference
15211                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15212                                // Application explicitly specified internal.
15213                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15214                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15215                                // App explictly prefers external. Let policy decide
15216                            } else {
15217                                // Prefer previous location
15218                                if (isExternal(installedPkg)) {
15219                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15220                                }
15221                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15222                            }
15223                        }
15224                    } else {
15225                        // Invalid install. Return error code
15226                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15227                    }
15228                }
15229            }
15230            // All the special cases have been taken care of.
15231            // Return result based on recommended install location.
15232            if (onSd) {
15233                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15234            }
15235            return pkgLite.recommendedInstallLocation;
15236        }
15237
15238        /*
15239         * Invoke remote method to get package information and install
15240         * location values. Override install location based on default
15241         * policy if needed and then create install arguments based
15242         * on the install location.
15243         */
15244        public void handleStartCopy() throws RemoteException {
15245            int ret = PackageManager.INSTALL_SUCCEEDED;
15246
15247            // If we're already staged, we've firmly committed to an install location
15248            if (origin.staged) {
15249                if (origin.file != null) {
15250                    installFlags |= PackageManager.INSTALL_INTERNAL;
15251                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15252                } else {
15253                    throw new IllegalStateException("Invalid stage location");
15254                }
15255            }
15256
15257            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15258            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15259            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15260            PackageInfoLite pkgLite = null;
15261
15262            if (onInt && onSd) {
15263                // Check if both bits are set.
15264                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15265                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15266            } else if (onSd && ephemeral) {
15267                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15268                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15269            } else {
15270                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15271                        packageAbiOverride);
15272
15273                if (DEBUG_INSTANT && ephemeral) {
15274                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15275                }
15276
15277                /*
15278                 * If we have too little free space, try to free cache
15279                 * before giving up.
15280                 */
15281                if (!origin.staged && pkgLite.recommendedInstallLocation
15282                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15283                    // TODO: focus freeing disk space on the target device
15284                    final StorageManager storage = StorageManager.from(mContext);
15285                    final long lowThreshold = storage.getStorageLowBytes(
15286                            Environment.getDataDirectory());
15287
15288                    final long sizeBytes = mContainerService.calculateInstalledSize(
15289                            origin.resolvedPath, packageAbiOverride);
15290
15291                    try {
15292                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15293                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15294                                installFlags, packageAbiOverride);
15295                    } catch (InstallerException e) {
15296                        Slog.w(TAG, "Failed to free cache", e);
15297                    }
15298
15299                    /*
15300                     * The cache free must have deleted the file we
15301                     * downloaded to install.
15302                     *
15303                     * TODO: fix the "freeCache" call to not delete
15304                     *       the file we care about.
15305                     */
15306                    if (pkgLite.recommendedInstallLocation
15307                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15308                        pkgLite.recommendedInstallLocation
15309                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15310                    }
15311                }
15312            }
15313
15314            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15315                int loc = pkgLite.recommendedInstallLocation;
15316                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15317                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15318                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15319                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15320                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15321                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15322                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15323                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15324                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15325                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15326                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15327                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15328                } else {
15329                    // Override with defaults if needed.
15330                    loc = installLocationPolicy(pkgLite);
15331                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15332                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15333                    } else if (!onSd && !onInt) {
15334                        // Override install location with flags
15335                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15336                            // Set the flag to install on external media.
15337                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15338                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15339                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15340                            if (DEBUG_INSTANT) {
15341                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15342                            }
15343                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15344                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15345                                    |PackageManager.INSTALL_INTERNAL);
15346                        } else {
15347                            // Make sure the flag for installing on external
15348                            // media is unset
15349                            installFlags |= PackageManager.INSTALL_INTERNAL;
15350                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15351                        }
15352                    }
15353                }
15354            }
15355
15356            final InstallArgs args = createInstallArgs(this);
15357            mArgs = args;
15358
15359            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15360                // TODO: http://b/22976637
15361                // Apps installed for "all" users use the device owner to verify the app
15362                UserHandle verifierUser = getUser();
15363                if (verifierUser == UserHandle.ALL) {
15364                    verifierUser = UserHandle.SYSTEM;
15365                }
15366
15367                /*
15368                 * Determine if we have any installed package verifiers. If we
15369                 * do, then we'll defer to them to verify the packages.
15370                 */
15371                final int requiredUid = mRequiredVerifierPackage == null ? -1
15372                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15373                                verifierUser.getIdentifier());
15374                final int installerUid =
15375                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15376                if (!origin.existing && requiredUid != -1
15377                        && isVerificationEnabled(
15378                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15379                    final Intent verification = new Intent(
15380                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15381                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15382                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15383                            PACKAGE_MIME_TYPE);
15384                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15385
15386                    // Query all live verifiers based on current user state
15387                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15388                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15389                            false /*allowDynamicSplits*/);
15390
15391                    if (DEBUG_VERIFY) {
15392                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15393                                + verification.toString() + " with " + pkgLite.verifiers.length
15394                                + " optional verifiers");
15395                    }
15396
15397                    final int verificationId = mPendingVerificationToken++;
15398
15399                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15400
15401                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15402                            installerPackageName);
15403
15404                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15405                            installFlags);
15406
15407                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15408                            pkgLite.packageName);
15409
15410                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15411                            pkgLite.versionCode);
15412
15413                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15414                            pkgLite.getLongVersionCode());
15415
15416                    if (verificationInfo != null) {
15417                        if (verificationInfo.originatingUri != null) {
15418                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15419                                    verificationInfo.originatingUri);
15420                        }
15421                        if (verificationInfo.referrer != null) {
15422                            verification.putExtra(Intent.EXTRA_REFERRER,
15423                                    verificationInfo.referrer);
15424                        }
15425                        if (verificationInfo.originatingUid >= 0) {
15426                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15427                                    verificationInfo.originatingUid);
15428                        }
15429                        if (verificationInfo.installerUid >= 0) {
15430                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15431                                    verificationInfo.installerUid);
15432                        }
15433                    }
15434
15435                    final PackageVerificationState verificationState = new PackageVerificationState(
15436                            requiredUid, args);
15437
15438                    mPendingVerification.append(verificationId, verificationState);
15439
15440                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15441                            receivers, verificationState);
15442
15443                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15444                    final long idleDuration = getVerificationTimeout();
15445
15446                    /*
15447                     * If any sufficient verifiers were listed in the package
15448                     * manifest, attempt to ask them.
15449                     */
15450                    if (sufficientVerifiers != null) {
15451                        final int N = sufficientVerifiers.size();
15452                        if (N == 0) {
15453                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15454                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15455                        } else {
15456                            for (int i = 0; i < N; i++) {
15457                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15458                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15459                                        verifierComponent.getPackageName(), idleDuration,
15460                                        verifierUser.getIdentifier(), false, "package verifier");
15461
15462                                final Intent sufficientIntent = new Intent(verification);
15463                                sufficientIntent.setComponent(verifierComponent);
15464                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15465                            }
15466                        }
15467                    }
15468
15469                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15470                            mRequiredVerifierPackage, receivers);
15471                    if (ret == PackageManager.INSTALL_SUCCEEDED
15472                            && mRequiredVerifierPackage != null) {
15473                        Trace.asyncTraceBegin(
15474                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15475                        /*
15476                         * Send the intent to the required verification agent,
15477                         * but only start the verification timeout after the
15478                         * target BroadcastReceivers have run.
15479                         */
15480                        verification.setComponent(requiredVerifierComponent);
15481                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15482                                mRequiredVerifierPackage, idleDuration,
15483                                verifierUser.getIdentifier(), false, "package verifier");
15484                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15485                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15486                                new BroadcastReceiver() {
15487                                    @Override
15488                                    public void onReceive(Context context, Intent intent) {
15489                                        final Message msg = mHandler
15490                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15491                                        msg.arg1 = verificationId;
15492                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15493                                    }
15494                                }, null, 0, null, null);
15495
15496                        /*
15497                         * We don't want the copy to proceed until verification
15498                         * succeeds, so null out this field.
15499                         */
15500                        mArgs = null;
15501                    }
15502                } else {
15503                    /*
15504                     * No package verification is enabled, so immediately start
15505                     * the remote call to initiate copy using temporary file.
15506                     */
15507                    ret = args.copyApk(mContainerService, true);
15508                }
15509            }
15510
15511            mRet = ret;
15512        }
15513
15514        @Override
15515        void handleReturnCode() {
15516            // If mArgs is null, then MCS couldn't be reached. When it
15517            // reconnects, it will try again to install. At that point, this
15518            // will succeed.
15519            if (mArgs != null) {
15520                processPendingInstall(mArgs, mRet);
15521            }
15522        }
15523
15524        @Override
15525        void handleServiceError() {
15526            mArgs = createInstallArgs(this);
15527            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15528        }
15529    }
15530
15531    private InstallArgs createInstallArgs(InstallParams params) {
15532        if (params.move != null) {
15533            return new MoveInstallArgs(params);
15534        } else {
15535            return new FileInstallArgs(params);
15536        }
15537    }
15538
15539    /**
15540     * Create args that describe an existing installed package. Typically used
15541     * when cleaning up old installs, or used as a move source.
15542     */
15543    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15544            String resourcePath, String[] instructionSets) {
15545        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15546    }
15547
15548    static abstract class InstallArgs {
15549        /** @see InstallParams#origin */
15550        final OriginInfo origin;
15551        /** @see InstallParams#move */
15552        final MoveInfo move;
15553
15554        final IPackageInstallObserver2 observer;
15555        // Always refers to PackageManager flags only
15556        final int installFlags;
15557        final String installerPackageName;
15558        final String volumeUuid;
15559        final UserHandle user;
15560        final String abiOverride;
15561        final String[] installGrantPermissions;
15562        /** If non-null, drop an async trace when the install completes */
15563        final String traceMethod;
15564        final int traceCookie;
15565        final PackageParser.SigningDetails signingDetails;
15566        final int installReason;
15567
15568        // The list of instruction sets supported by this app. This is currently
15569        // only used during the rmdex() phase to clean up resources. We can get rid of this
15570        // if we move dex files under the common app path.
15571        /* nullable */ String[] instructionSets;
15572
15573        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15574                int installFlags, String installerPackageName, String volumeUuid,
15575                UserHandle user, String[] instructionSets,
15576                String abiOverride, String[] installGrantPermissions,
15577                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15578                int installReason) {
15579            this.origin = origin;
15580            this.move = move;
15581            this.installFlags = installFlags;
15582            this.observer = observer;
15583            this.installerPackageName = installerPackageName;
15584            this.volumeUuid = volumeUuid;
15585            this.user = user;
15586            this.instructionSets = instructionSets;
15587            this.abiOverride = abiOverride;
15588            this.installGrantPermissions = installGrantPermissions;
15589            this.traceMethod = traceMethod;
15590            this.traceCookie = traceCookie;
15591            this.signingDetails = signingDetails;
15592            this.installReason = installReason;
15593        }
15594
15595        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15596        abstract int doPreInstall(int status);
15597
15598        /**
15599         * Rename package into final resting place. All paths on the given
15600         * scanned package should be updated to reflect the rename.
15601         */
15602        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15603        abstract int doPostInstall(int status, int uid);
15604
15605        /** @see PackageSettingBase#codePathString */
15606        abstract String getCodePath();
15607        /** @see PackageSettingBase#resourcePathString */
15608        abstract String getResourcePath();
15609
15610        // Need installer lock especially for dex file removal.
15611        abstract void cleanUpResourcesLI();
15612        abstract boolean doPostDeleteLI(boolean delete);
15613
15614        /**
15615         * Called before the source arguments are copied. This is used mostly
15616         * for MoveParams when it needs to read the source file to put it in the
15617         * destination.
15618         */
15619        int doPreCopy() {
15620            return PackageManager.INSTALL_SUCCEEDED;
15621        }
15622
15623        /**
15624         * Called after the source arguments are copied. This is used mostly for
15625         * MoveParams when it needs to read the source file to put it in the
15626         * destination.
15627         */
15628        int doPostCopy(int uid) {
15629            return PackageManager.INSTALL_SUCCEEDED;
15630        }
15631
15632        protected boolean isFwdLocked() {
15633            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15634        }
15635
15636        protected boolean isExternalAsec() {
15637            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15638        }
15639
15640        protected boolean isEphemeral() {
15641            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15642        }
15643
15644        UserHandle getUser() {
15645            return user;
15646        }
15647    }
15648
15649    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15650        if (!allCodePaths.isEmpty()) {
15651            if (instructionSets == null) {
15652                throw new IllegalStateException("instructionSet == null");
15653            }
15654            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15655            for (String codePath : allCodePaths) {
15656                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15657                    try {
15658                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15659                    } catch (InstallerException ignored) {
15660                    }
15661                }
15662            }
15663        }
15664    }
15665
15666    /**
15667     * Logic to handle installation of non-ASEC applications, including copying
15668     * and renaming logic.
15669     */
15670    class FileInstallArgs extends InstallArgs {
15671        private File codeFile;
15672        private File resourceFile;
15673
15674        // Example topology:
15675        // /data/app/com.example/base.apk
15676        // /data/app/com.example/split_foo.apk
15677        // /data/app/com.example/lib/arm/libfoo.so
15678        // /data/app/com.example/lib/arm64/libfoo.so
15679        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15680
15681        /** New install */
15682        FileInstallArgs(InstallParams params) {
15683            super(params.origin, params.move, params.observer, params.installFlags,
15684                    params.installerPackageName, params.volumeUuid,
15685                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15686                    params.grantedRuntimePermissions,
15687                    params.traceMethod, params.traceCookie, params.signingDetails,
15688                    params.installReason);
15689            if (isFwdLocked()) {
15690                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15691            }
15692        }
15693
15694        /** Existing install */
15695        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15696            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15697                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15698                    PackageManager.INSTALL_REASON_UNKNOWN);
15699            this.codeFile = (codePath != null) ? new File(codePath) : null;
15700            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15701        }
15702
15703        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15704            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15705            try {
15706                return doCopyApk(imcs, temp);
15707            } finally {
15708                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15709            }
15710        }
15711
15712        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15713            if (origin.staged) {
15714                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15715                codeFile = origin.file;
15716                resourceFile = origin.file;
15717                return PackageManager.INSTALL_SUCCEEDED;
15718            }
15719
15720            try {
15721                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15722                final File tempDir =
15723                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15724                codeFile = tempDir;
15725                resourceFile = tempDir;
15726            } catch (IOException e) {
15727                Slog.w(TAG, "Failed to create copy file: " + e);
15728                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15729            }
15730
15731            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15732                @Override
15733                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15734                    if (!FileUtils.isValidExtFilename(name)) {
15735                        throw new IllegalArgumentException("Invalid filename: " + name);
15736                    }
15737                    try {
15738                        final File file = new File(codeFile, name);
15739                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15740                                O_RDWR | O_CREAT, 0644);
15741                        Os.chmod(file.getAbsolutePath(), 0644);
15742                        return new ParcelFileDescriptor(fd);
15743                    } catch (ErrnoException e) {
15744                        throw new RemoteException("Failed to open: " + e.getMessage());
15745                    }
15746                }
15747            };
15748
15749            int ret = PackageManager.INSTALL_SUCCEEDED;
15750            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15751            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15752                Slog.e(TAG, "Failed to copy package");
15753                return ret;
15754            }
15755
15756            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15757            NativeLibraryHelper.Handle handle = null;
15758            try {
15759                handle = NativeLibraryHelper.Handle.create(codeFile);
15760                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15761                        abiOverride);
15762            } catch (IOException e) {
15763                Slog.e(TAG, "Copying native libraries failed", e);
15764                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15765            } finally {
15766                IoUtils.closeQuietly(handle);
15767            }
15768
15769            return ret;
15770        }
15771
15772        int doPreInstall(int status) {
15773            if (status != PackageManager.INSTALL_SUCCEEDED) {
15774                cleanUp();
15775            }
15776            return status;
15777        }
15778
15779        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15780            if (status != PackageManager.INSTALL_SUCCEEDED) {
15781                cleanUp();
15782                return false;
15783            }
15784
15785            final File targetDir = codeFile.getParentFile();
15786            final File beforeCodeFile = codeFile;
15787            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15788
15789            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15790            try {
15791                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15792            } catch (ErrnoException e) {
15793                Slog.w(TAG, "Failed to rename", e);
15794                return false;
15795            }
15796
15797            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15798                Slog.w(TAG, "Failed to restorecon");
15799                return false;
15800            }
15801
15802            // Reflect the rename internally
15803            codeFile = afterCodeFile;
15804            resourceFile = afterCodeFile;
15805
15806            // Reflect the rename in scanned details
15807            try {
15808                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15809            } catch (IOException e) {
15810                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15811                return false;
15812            }
15813            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15814                    afterCodeFile, pkg.baseCodePath));
15815            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15816                    afterCodeFile, pkg.splitCodePaths));
15817
15818            // Reflect the rename in app info
15819            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15820            pkg.setApplicationInfoCodePath(pkg.codePath);
15821            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15822            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15823            pkg.setApplicationInfoResourcePath(pkg.codePath);
15824            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15825            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15826
15827            return true;
15828        }
15829
15830        int doPostInstall(int status, int uid) {
15831            if (status != PackageManager.INSTALL_SUCCEEDED) {
15832                cleanUp();
15833            }
15834            return status;
15835        }
15836
15837        @Override
15838        String getCodePath() {
15839            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15840        }
15841
15842        @Override
15843        String getResourcePath() {
15844            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15845        }
15846
15847        private boolean cleanUp() {
15848            if (codeFile == null || !codeFile.exists()) {
15849                return false;
15850            }
15851
15852            removeCodePathLI(codeFile);
15853
15854            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15855                resourceFile.delete();
15856            }
15857
15858            return true;
15859        }
15860
15861        void cleanUpResourcesLI() {
15862            // Try enumerating all code paths before deleting
15863            List<String> allCodePaths = Collections.EMPTY_LIST;
15864            if (codeFile != null && codeFile.exists()) {
15865                try {
15866                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15867                    allCodePaths = pkg.getAllCodePaths();
15868                } catch (PackageParserException e) {
15869                    // Ignored; we tried our best
15870                }
15871            }
15872
15873            cleanUp();
15874            removeDexFiles(allCodePaths, instructionSets);
15875        }
15876
15877        boolean doPostDeleteLI(boolean delete) {
15878            // XXX err, shouldn't we respect the delete flag?
15879            cleanUpResourcesLI();
15880            return true;
15881        }
15882    }
15883
15884    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15885            PackageManagerException {
15886        if (copyRet < 0) {
15887            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15888                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15889                throw new PackageManagerException(copyRet, message);
15890            }
15891        }
15892    }
15893
15894    /**
15895     * Extract the StorageManagerService "container ID" from the full code path of an
15896     * .apk.
15897     */
15898    static String cidFromCodePath(String fullCodePath) {
15899        int eidx = fullCodePath.lastIndexOf("/");
15900        String subStr1 = fullCodePath.substring(0, eidx);
15901        int sidx = subStr1.lastIndexOf("/");
15902        return subStr1.substring(sidx+1, eidx);
15903    }
15904
15905    /**
15906     * Logic to handle movement of existing installed applications.
15907     */
15908    class MoveInstallArgs extends InstallArgs {
15909        private File codeFile;
15910        private File resourceFile;
15911
15912        /** New install */
15913        MoveInstallArgs(InstallParams params) {
15914            super(params.origin, params.move, params.observer, params.installFlags,
15915                    params.installerPackageName, params.volumeUuid,
15916                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15917                    params.grantedRuntimePermissions,
15918                    params.traceMethod, params.traceCookie, params.signingDetails,
15919                    params.installReason);
15920        }
15921
15922        int copyApk(IMediaContainerService imcs, boolean temp) {
15923            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15924                    + move.fromUuid + " to " + move.toUuid);
15925            synchronized (mInstaller) {
15926                try {
15927                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15928                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15929                } catch (InstallerException e) {
15930                    Slog.w(TAG, "Failed to move app", e);
15931                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15932                }
15933            }
15934
15935            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15936            resourceFile = codeFile;
15937            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15938
15939            return PackageManager.INSTALL_SUCCEEDED;
15940        }
15941
15942        int doPreInstall(int status) {
15943            if (status != PackageManager.INSTALL_SUCCEEDED) {
15944                cleanUp(move.toUuid);
15945            }
15946            return status;
15947        }
15948
15949        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15950            if (status != PackageManager.INSTALL_SUCCEEDED) {
15951                cleanUp(move.toUuid);
15952                return false;
15953            }
15954
15955            // Reflect the move in app info
15956            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15957            pkg.setApplicationInfoCodePath(pkg.codePath);
15958            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15959            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15960            pkg.setApplicationInfoResourcePath(pkg.codePath);
15961            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15962            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15963
15964            return true;
15965        }
15966
15967        int doPostInstall(int status, int uid) {
15968            if (status == PackageManager.INSTALL_SUCCEEDED) {
15969                cleanUp(move.fromUuid);
15970            } else {
15971                cleanUp(move.toUuid);
15972            }
15973            return status;
15974        }
15975
15976        @Override
15977        String getCodePath() {
15978            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15979        }
15980
15981        @Override
15982        String getResourcePath() {
15983            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15984        }
15985
15986        private boolean cleanUp(String volumeUuid) {
15987            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15988                    move.dataAppName);
15989            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15990            final int[] userIds = sUserManager.getUserIds();
15991            synchronized (mInstallLock) {
15992                // Clean up both app data and code
15993                // All package moves are frozen until finished
15994                for (int userId : userIds) {
15995                    try {
15996                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15997                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15998                    } catch (InstallerException e) {
15999                        Slog.w(TAG, String.valueOf(e));
16000                    }
16001                }
16002                removeCodePathLI(codeFile);
16003            }
16004            return true;
16005        }
16006
16007        void cleanUpResourcesLI() {
16008            throw new UnsupportedOperationException();
16009        }
16010
16011        boolean doPostDeleteLI(boolean delete) {
16012            throw new UnsupportedOperationException();
16013        }
16014    }
16015
16016    static String getAsecPackageName(String packageCid) {
16017        int idx = packageCid.lastIndexOf("-");
16018        if (idx == -1) {
16019            return packageCid;
16020        }
16021        return packageCid.substring(0, idx);
16022    }
16023
16024    // Utility method used to create code paths based on package name and available index.
16025    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16026        String idxStr = "";
16027        int idx = 1;
16028        // Fall back to default value of idx=1 if prefix is not
16029        // part of oldCodePath
16030        if (oldCodePath != null) {
16031            String subStr = oldCodePath;
16032            // Drop the suffix right away
16033            if (suffix != null && subStr.endsWith(suffix)) {
16034                subStr = subStr.substring(0, subStr.length() - suffix.length());
16035            }
16036            // If oldCodePath already contains prefix find out the
16037            // ending index to either increment or decrement.
16038            int sidx = subStr.lastIndexOf(prefix);
16039            if (sidx != -1) {
16040                subStr = subStr.substring(sidx + prefix.length());
16041                if (subStr != null) {
16042                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16043                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16044                    }
16045                    try {
16046                        idx = Integer.parseInt(subStr);
16047                        if (idx <= 1) {
16048                            idx++;
16049                        } else {
16050                            idx--;
16051                        }
16052                    } catch(NumberFormatException e) {
16053                    }
16054                }
16055            }
16056        }
16057        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16058        return prefix + idxStr;
16059    }
16060
16061    private File getNextCodePath(File targetDir, String packageName) {
16062        File result;
16063        SecureRandom random = new SecureRandom();
16064        byte[] bytes = new byte[16];
16065        do {
16066            random.nextBytes(bytes);
16067            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16068            result = new File(targetDir, packageName + "-" + suffix);
16069        } while (result.exists());
16070        return result;
16071    }
16072
16073    // Utility method that returns the relative package path with respect
16074    // to the installation directory. Like say for /data/data/com.test-1.apk
16075    // string com.test-1 is returned.
16076    static String deriveCodePathName(String codePath) {
16077        if (codePath == null) {
16078            return null;
16079        }
16080        final File codeFile = new File(codePath);
16081        final String name = codeFile.getName();
16082        if (codeFile.isDirectory()) {
16083            return name;
16084        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16085            final int lastDot = name.lastIndexOf('.');
16086            return name.substring(0, lastDot);
16087        } else {
16088            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16089            return null;
16090        }
16091    }
16092
16093    static class PackageInstalledInfo {
16094        String name;
16095        int uid;
16096        // The set of users that originally had this package installed.
16097        int[] origUsers;
16098        // The set of users that now have this package installed.
16099        int[] newUsers;
16100        PackageParser.Package pkg;
16101        int returnCode;
16102        String returnMsg;
16103        String installerPackageName;
16104        PackageRemovedInfo removedInfo;
16105        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16106
16107        public void setError(int code, String msg) {
16108            setReturnCode(code);
16109            setReturnMessage(msg);
16110            Slog.w(TAG, msg);
16111        }
16112
16113        public void setError(String msg, PackageParserException e) {
16114            setReturnCode(e.error);
16115            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16116            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16117            for (int i = 0; i < childCount; i++) {
16118                addedChildPackages.valueAt(i).setError(msg, e);
16119            }
16120            Slog.w(TAG, msg, e);
16121        }
16122
16123        public void setError(String msg, PackageManagerException e) {
16124            returnCode = e.error;
16125            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16126            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16127            for (int i = 0; i < childCount; i++) {
16128                addedChildPackages.valueAt(i).setError(msg, e);
16129            }
16130            Slog.w(TAG, msg, e);
16131        }
16132
16133        public void setReturnCode(int returnCode) {
16134            this.returnCode = returnCode;
16135            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16136            for (int i = 0; i < childCount; i++) {
16137                addedChildPackages.valueAt(i).returnCode = returnCode;
16138            }
16139        }
16140
16141        private void setReturnMessage(String returnMsg) {
16142            this.returnMsg = returnMsg;
16143            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16144            for (int i = 0; i < childCount; i++) {
16145                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16146            }
16147        }
16148
16149        // In some error cases we want to convey more info back to the observer
16150        String origPackage;
16151        String origPermission;
16152    }
16153
16154    /*
16155     * Install a non-existing package.
16156     */
16157    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16158            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16159            String volumeUuid, PackageInstalledInfo res, int installReason) {
16160        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16161
16162        // Remember this for later, in case we need to rollback this install
16163        String pkgName = pkg.packageName;
16164
16165        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16166
16167        synchronized(mPackages) {
16168            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16169            if (renamedPackage != null) {
16170                // A package with the same name is already installed, though
16171                // it has been renamed to an older name.  The package we
16172                // are trying to install should be installed as an update to
16173                // the existing one, but that has not been requested, so bail.
16174                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16175                        + " without first uninstalling package running as "
16176                        + renamedPackage);
16177                return;
16178            }
16179            if (mPackages.containsKey(pkgName)) {
16180                // Don't allow installation over an existing package with the same name.
16181                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16182                        + " without first uninstalling.");
16183                return;
16184            }
16185        }
16186
16187        try {
16188            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16189                    System.currentTimeMillis(), user);
16190
16191            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16192
16193            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16194                prepareAppDataAfterInstallLIF(newPackage);
16195
16196            } else {
16197                // Remove package from internal structures, but keep around any
16198                // data that might have already existed
16199                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16200                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16201            }
16202        } catch (PackageManagerException e) {
16203            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16204        }
16205
16206        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16207    }
16208
16209    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16210        try (DigestInputStream digestStream =
16211                new DigestInputStream(new FileInputStream(file), digest)) {
16212            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16213        }
16214    }
16215
16216    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16217            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16218            PackageInstalledInfo res, int installReason) {
16219        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16220
16221        final PackageParser.Package oldPackage;
16222        final PackageSetting ps;
16223        final String pkgName = pkg.packageName;
16224        final int[] allUsers;
16225        final int[] installedUsers;
16226
16227        synchronized(mPackages) {
16228            oldPackage = mPackages.get(pkgName);
16229            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16230
16231            // don't allow upgrade to target a release SDK from a pre-release SDK
16232            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16233                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16234            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16235                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16236            if (oldTargetsPreRelease
16237                    && !newTargetsPreRelease
16238                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16239                Slog.w(TAG, "Can't install package targeting released sdk");
16240                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16241                return;
16242            }
16243
16244            ps = mSettings.mPackages.get(pkgName);
16245
16246            // verify signatures are valid
16247            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16248            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16249                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16250                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16251                            "New package not signed by keys specified by upgrade-keysets: "
16252                                    + pkgName);
16253                    return;
16254                }
16255            } else {
16256
16257                // default to original signature matching
16258                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16259                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16260                                && !oldPackage.mSigningDetails.checkCapability(
16261                                        pkg.mSigningDetails,
16262                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16263                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16264                            "New package has a different signature: " + pkgName);
16265                    return;
16266                }
16267            }
16268
16269            // don't allow a system upgrade unless the upgrade hash matches
16270            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16271                byte[] digestBytes = null;
16272                try {
16273                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16274                    updateDigest(digest, new File(pkg.baseCodePath));
16275                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16276                        for (String path : pkg.splitCodePaths) {
16277                            updateDigest(digest, new File(path));
16278                        }
16279                    }
16280                    digestBytes = digest.digest();
16281                } catch (NoSuchAlgorithmException | IOException e) {
16282                    res.setError(INSTALL_FAILED_INVALID_APK,
16283                            "Could not compute hash: " + pkgName);
16284                    return;
16285                }
16286                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16287                    res.setError(INSTALL_FAILED_INVALID_APK,
16288                            "New package fails restrict-update check: " + pkgName);
16289                    return;
16290                }
16291                // retain upgrade restriction
16292                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16293            }
16294
16295            // Check for shared user id changes
16296            String invalidPackageName =
16297                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16298            if (invalidPackageName != null) {
16299                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16300                        "Package " + invalidPackageName + " tried to change user "
16301                                + oldPackage.mSharedUserId);
16302                return;
16303            }
16304
16305            // check if the new package supports all of the abis which the old package supports
16306            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16307            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16308            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16309                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16310                        "Update to package " + pkgName + " doesn't support multi arch");
16311                return;
16312            }
16313
16314            // In case of rollback, remember per-user/profile install state
16315            allUsers = sUserManager.getUserIds();
16316            installedUsers = ps.queryInstalledUsers(allUsers, true);
16317
16318            // don't allow an upgrade from full to ephemeral
16319            if (isInstantApp) {
16320                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16321                    for (int currentUser : allUsers) {
16322                        if (!ps.getInstantApp(currentUser)) {
16323                            // can't downgrade from full to instant
16324                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16325                                    + " for user: " + currentUser);
16326                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16327                            return;
16328                        }
16329                    }
16330                } else if (!ps.getInstantApp(user.getIdentifier())) {
16331                    // can't downgrade from full to instant
16332                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16333                            + " for user: " + user.getIdentifier());
16334                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16335                    return;
16336                }
16337            }
16338        }
16339
16340        // Update what is removed
16341        res.removedInfo = new PackageRemovedInfo(this);
16342        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16343        res.removedInfo.removedPackage = oldPackage.packageName;
16344        res.removedInfo.installerPackageName = ps.installerPackageName;
16345        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16346        res.removedInfo.isUpdate = true;
16347        res.removedInfo.origUsers = installedUsers;
16348        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16349        for (int i = 0; i < installedUsers.length; i++) {
16350            final int userId = installedUsers[i];
16351            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16352        }
16353
16354        final int childCount = (oldPackage.childPackages != null)
16355                ? oldPackage.childPackages.size() : 0;
16356        for (int i = 0; i < childCount; i++) {
16357            boolean childPackageUpdated = false;
16358            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16359            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16360            if (res.addedChildPackages != null) {
16361                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16362                if (childRes != null) {
16363                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16364                    childRes.removedInfo.removedPackage = childPkg.packageName;
16365                    if (childPs != null) {
16366                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16367                    }
16368                    childRes.removedInfo.isUpdate = true;
16369                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16370                    childPackageUpdated = true;
16371                }
16372            }
16373            if (!childPackageUpdated) {
16374                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16375                childRemovedRes.removedPackage = childPkg.packageName;
16376                if (childPs != null) {
16377                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16378                }
16379                childRemovedRes.isUpdate = false;
16380                childRemovedRes.dataRemoved = true;
16381                synchronized (mPackages) {
16382                    if (childPs != null) {
16383                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16384                    }
16385                }
16386                if (res.removedInfo.removedChildPackages == null) {
16387                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16388                }
16389                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16390            }
16391        }
16392
16393        boolean sysPkg = (isSystemApp(oldPackage));
16394        if (sysPkg) {
16395            // Set the system/privileged/oem/vendor/product flags as needed
16396            final boolean privileged =
16397                    (oldPackage.applicationInfo.privateFlags
16398                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16399            final boolean oem =
16400                    (oldPackage.applicationInfo.privateFlags
16401                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16402            final boolean vendor =
16403                    (oldPackage.applicationInfo.privateFlags
16404                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16405            final boolean product =
16406                    (oldPackage.applicationInfo.privateFlags
16407                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16408            final @ParseFlags int systemParseFlags = parseFlags;
16409            final @ScanFlags int systemScanFlags = scanFlags
16410                    | SCAN_AS_SYSTEM
16411                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16412                    | (oem ? SCAN_AS_OEM : 0)
16413                    | (vendor ? SCAN_AS_VENDOR : 0)
16414                    | (product ? SCAN_AS_PRODUCT : 0);
16415
16416            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16417                    user, allUsers, installerPackageName, res, installReason);
16418        } else {
16419            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16420                    user, allUsers, installerPackageName, res, installReason);
16421        }
16422    }
16423
16424    @Override
16425    public List<String> getPreviousCodePaths(String packageName) {
16426        final int callingUid = Binder.getCallingUid();
16427        final List<String> result = new ArrayList<>();
16428        if (getInstantAppPackageName(callingUid) != null) {
16429            return result;
16430        }
16431        final PackageSetting ps = mSettings.mPackages.get(packageName);
16432        if (ps != null
16433                && ps.oldCodePaths != null
16434                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16435            result.addAll(ps.oldCodePaths);
16436        }
16437        return result;
16438    }
16439
16440    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16441            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16442            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16443            String installerPackageName, PackageInstalledInfo res, int installReason) {
16444        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16445                + deletedPackage);
16446
16447        String pkgName = deletedPackage.packageName;
16448        boolean deletedPkg = true;
16449        boolean addedPkg = false;
16450        boolean updatedSettings = false;
16451        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16452        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16453                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16454
16455        final long origUpdateTime = (pkg.mExtras != null)
16456                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16457
16458        // First delete the existing package while retaining the data directory
16459        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16460                res.removedInfo, true, pkg)) {
16461            // If the existing package wasn't successfully deleted
16462            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16463            deletedPkg = false;
16464        } else {
16465            // Successfully deleted the old package; proceed with replace.
16466
16467            // If deleted package lived in a container, give users a chance to
16468            // relinquish resources before killing.
16469            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16470                if (DEBUG_INSTALL) {
16471                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16472                }
16473                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16474                final ArrayList<String> pkgList = new ArrayList<String>(1);
16475                pkgList.add(deletedPackage.applicationInfo.packageName);
16476                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16477            }
16478
16479            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16480                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16481
16482            try {
16483                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16484                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16485                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16486                        installReason);
16487
16488                // Update the in-memory copy of the previous code paths.
16489                PackageSetting ps = mSettings.mPackages.get(pkgName);
16490                if (!killApp) {
16491                    if (ps.oldCodePaths == null) {
16492                        ps.oldCodePaths = new ArraySet<>();
16493                    }
16494                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16495                    if (deletedPackage.splitCodePaths != null) {
16496                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16497                    }
16498                } else {
16499                    ps.oldCodePaths = null;
16500                }
16501                if (ps.childPackageNames != null) {
16502                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16503                        final String childPkgName = ps.childPackageNames.get(i);
16504                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16505                        childPs.oldCodePaths = ps.oldCodePaths;
16506                    }
16507                }
16508                prepareAppDataAfterInstallLIF(newPackage);
16509                addedPkg = true;
16510                mDexManager.notifyPackageUpdated(newPackage.packageName,
16511                        newPackage.baseCodePath, newPackage.splitCodePaths);
16512            } catch (PackageManagerException e) {
16513                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16514            }
16515        }
16516
16517        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16518            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16519
16520            // Revert all internal state mutations and added folders for the failed install
16521            if (addedPkg) {
16522                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16523                        res.removedInfo, true, null);
16524            }
16525
16526            // Restore the old package
16527            if (deletedPkg) {
16528                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16529                File restoreFile = new File(deletedPackage.codePath);
16530                // Parse old package
16531                boolean oldExternal = isExternal(deletedPackage);
16532                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16533                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16534                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16535                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16536                try {
16537                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16538                            null);
16539                } catch (PackageManagerException e) {
16540                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16541                            + e.getMessage());
16542                    return;
16543                }
16544
16545                synchronized (mPackages) {
16546                    // Ensure the installer package name up to date
16547                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16548
16549                    // Update permissions for restored package
16550                    mPermissionManager.updatePermissions(
16551                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16552                            mPermissionCallback);
16553
16554                    mSettings.writeLPr();
16555                }
16556
16557                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16558            }
16559        } else {
16560            synchronized (mPackages) {
16561                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16562                if (ps != null) {
16563                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16564                    if (res.removedInfo.removedChildPackages != null) {
16565                        final int childCount = res.removedInfo.removedChildPackages.size();
16566                        // Iterate in reverse as we may modify the collection
16567                        for (int i = childCount - 1; i >= 0; i--) {
16568                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16569                            if (res.addedChildPackages.containsKey(childPackageName)) {
16570                                res.removedInfo.removedChildPackages.removeAt(i);
16571                            } else {
16572                                PackageRemovedInfo childInfo = res.removedInfo
16573                                        .removedChildPackages.valueAt(i);
16574                                childInfo.removedForAllUsers = mPackages.get(
16575                                        childInfo.removedPackage) == null;
16576                            }
16577                        }
16578                    }
16579                }
16580            }
16581        }
16582    }
16583
16584    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16585            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16586            final @ScanFlags int scanFlags, UserHandle user,
16587            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16588            int installReason) {
16589        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16590                + ", old=" + deletedPackage);
16591
16592        final boolean disabledSystem;
16593
16594        // Remove existing system package
16595        removePackageLI(deletedPackage, true);
16596
16597        synchronized (mPackages) {
16598            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16599        }
16600        if (!disabledSystem) {
16601            // We didn't need to disable the .apk as a current system package,
16602            // which means we are replacing another update that is already
16603            // installed.  We need to make sure to delete the older one's .apk.
16604            res.removedInfo.args = createInstallArgsForExisting(0,
16605                    deletedPackage.applicationInfo.getCodePath(),
16606                    deletedPackage.applicationInfo.getResourcePath(),
16607                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16608        } else {
16609            res.removedInfo.args = null;
16610        }
16611
16612        // Successfully disabled the old package. Now proceed with re-installation
16613        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16614                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16615
16616        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16617        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16618                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16619
16620        PackageParser.Package newPackage = null;
16621        try {
16622            // Add the package to the internal data structures
16623            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16624
16625            // Set the update and install times
16626            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16627            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16628                    System.currentTimeMillis());
16629
16630            // Update the package dynamic state if succeeded
16631            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16632                // Now that the install succeeded make sure we remove data
16633                // directories for any child package the update removed.
16634                final int deletedChildCount = (deletedPackage.childPackages != null)
16635                        ? deletedPackage.childPackages.size() : 0;
16636                final int newChildCount = (newPackage.childPackages != null)
16637                        ? newPackage.childPackages.size() : 0;
16638                for (int i = 0; i < deletedChildCount; i++) {
16639                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16640                    boolean childPackageDeleted = true;
16641                    for (int j = 0; j < newChildCount; j++) {
16642                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16643                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16644                            childPackageDeleted = false;
16645                            break;
16646                        }
16647                    }
16648                    if (childPackageDeleted) {
16649                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16650                                deletedChildPkg.packageName);
16651                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16652                            PackageRemovedInfo removedChildRes = res.removedInfo
16653                                    .removedChildPackages.get(deletedChildPkg.packageName);
16654                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16655                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16656                        }
16657                    }
16658                }
16659
16660                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16661                        installReason);
16662                prepareAppDataAfterInstallLIF(newPackage);
16663
16664                mDexManager.notifyPackageUpdated(newPackage.packageName,
16665                            newPackage.baseCodePath, newPackage.splitCodePaths);
16666            }
16667        } catch (PackageManagerException e) {
16668            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16669            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16670        }
16671
16672        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16673            // Re installation failed. Restore old information
16674            // Remove new pkg information
16675            if (newPackage != null) {
16676                removeInstalledPackageLI(newPackage, true);
16677            }
16678            // Add back the old system package
16679            try {
16680                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16681            } catch (PackageManagerException e) {
16682                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16683            }
16684
16685            synchronized (mPackages) {
16686                if (disabledSystem) {
16687                    enableSystemPackageLPw(deletedPackage);
16688                }
16689
16690                // Ensure the installer package name up to date
16691                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16692
16693                // Update permissions for restored package
16694                mPermissionManager.updatePermissions(
16695                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16696                        mPermissionCallback);
16697
16698                mSettings.writeLPr();
16699            }
16700
16701            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16702                    + " after failed upgrade");
16703        }
16704    }
16705
16706    /**
16707     * Checks whether the parent or any of the child packages have a change shared
16708     * user. For a package to be a valid update the shred users of the parent and
16709     * the children should match. We may later support changing child shared users.
16710     * @param oldPkg The updated package.
16711     * @param newPkg The update package.
16712     * @return The shared user that change between the versions.
16713     */
16714    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16715            PackageParser.Package newPkg) {
16716        // Check parent shared user
16717        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16718            return newPkg.packageName;
16719        }
16720        // Check child shared users
16721        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16722        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16723        for (int i = 0; i < newChildCount; i++) {
16724            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16725            // If this child was present, did it have the same shared user?
16726            for (int j = 0; j < oldChildCount; j++) {
16727                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16728                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16729                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16730                    return newChildPkg.packageName;
16731                }
16732            }
16733        }
16734        return null;
16735    }
16736
16737    private void removeNativeBinariesLI(PackageSetting ps) {
16738        // Remove the lib path for the parent package
16739        if (ps != null) {
16740            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16741            // Remove the lib path for the child packages
16742            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16743            for (int i = 0; i < childCount; i++) {
16744                PackageSetting childPs = null;
16745                synchronized (mPackages) {
16746                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16747                }
16748                if (childPs != null) {
16749                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16750                            .legacyNativeLibraryPathString);
16751                }
16752            }
16753        }
16754    }
16755
16756    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16757        // Enable the parent package
16758        mSettings.enableSystemPackageLPw(pkg.packageName);
16759        // Enable the child packages
16760        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16761        for (int i = 0; i < childCount; i++) {
16762            PackageParser.Package childPkg = pkg.childPackages.get(i);
16763            mSettings.enableSystemPackageLPw(childPkg.packageName);
16764        }
16765    }
16766
16767    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16768            PackageParser.Package newPkg) {
16769        // Disable the parent package (parent always replaced)
16770        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16771        // Disable the child packages
16772        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16773        for (int i = 0; i < childCount; i++) {
16774            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16775            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16776            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16777        }
16778        return disabled;
16779    }
16780
16781    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16782            String installerPackageName) {
16783        // Enable the parent package
16784        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16785        // Enable the child packages
16786        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16787        for (int i = 0; i < childCount; i++) {
16788            PackageParser.Package childPkg = pkg.childPackages.get(i);
16789            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16790        }
16791    }
16792
16793    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16794            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16795        // Update the parent package setting
16796        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16797                res, user, installReason);
16798        // Update the child packages setting
16799        final int childCount = (newPackage.childPackages != null)
16800                ? newPackage.childPackages.size() : 0;
16801        for (int i = 0; i < childCount; i++) {
16802            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16803            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16804            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16805                    childRes.origUsers, childRes, user, installReason);
16806        }
16807    }
16808
16809    private void updateSettingsInternalLI(PackageParser.Package pkg,
16810            String installerPackageName, int[] allUsers, int[] installedForUsers,
16811            PackageInstalledInfo res, UserHandle user, int installReason) {
16812        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16813
16814        final String pkgName = pkg.packageName;
16815
16816        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16817        synchronized (mPackages) {
16818// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16819            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16820                    mPermissionCallback);
16821            // For system-bundled packages, we assume that installing an upgraded version
16822            // of the package implies that the user actually wants to run that new code,
16823            // so we enable the package.
16824            PackageSetting ps = mSettings.mPackages.get(pkgName);
16825            final int userId = user.getIdentifier();
16826            if (ps != null) {
16827                if (isSystemApp(pkg)) {
16828                    if (DEBUG_INSTALL) {
16829                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16830                    }
16831                    // Enable system package for requested users
16832                    if (res.origUsers != null) {
16833                        for (int origUserId : res.origUsers) {
16834                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16835                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16836                                        origUserId, installerPackageName);
16837                            }
16838                        }
16839                    }
16840                    // Also convey the prior install/uninstall state
16841                    if (allUsers != null && installedForUsers != null) {
16842                        for (int currentUserId : allUsers) {
16843                            final boolean installed = ArrayUtils.contains(
16844                                    installedForUsers, currentUserId);
16845                            if (DEBUG_INSTALL) {
16846                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16847                            }
16848                            ps.setInstalled(installed, currentUserId);
16849                        }
16850                        // these install state changes will be persisted in the
16851                        // upcoming call to mSettings.writeLPr().
16852                    }
16853                }
16854                // It's implied that when a user requests installation, they want the app to be
16855                // installed and enabled.
16856                if (userId != UserHandle.USER_ALL) {
16857                    ps.setInstalled(true, userId);
16858                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16859                }
16860
16861                // When replacing an existing package, preserve the original install reason for all
16862                // users that had the package installed before.
16863                final Set<Integer> previousUserIds = new ArraySet<>();
16864                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16865                    final int installReasonCount = res.removedInfo.installReasons.size();
16866                    for (int i = 0; i < installReasonCount; i++) {
16867                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16868                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16869                        ps.setInstallReason(previousInstallReason, previousUserId);
16870                        previousUserIds.add(previousUserId);
16871                    }
16872                }
16873
16874                // Set install reason for users that are having the package newly installed.
16875                if (userId == UserHandle.USER_ALL) {
16876                    for (int currentUserId : sUserManager.getUserIds()) {
16877                        if (!previousUserIds.contains(currentUserId)) {
16878                            ps.setInstallReason(installReason, currentUserId);
16879                        }
16880                    }
16881                } else if (!previousUserIds.contains(userId)) {
16882                    ps.setInstallReason(installReason, userId);
16883                }
16884                mSettings.writeKernelMappingLPr(ps);
16885            }
16886            res.name = pkgName;
16887            res.uid = pkg.applicationInfo.uid;
16888            res.pkg = pkg;
16889            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16890            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16891            //to update install status
16892            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16893            mSettings.writeLPr();
16894            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16895        }
16896
16897        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16898    }
16899
16900    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16901        try {
16902            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16903            installPackageLI(args, res);
16904        } finally {
16905            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16906        }
16907    }
16908
16909    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16910        final int installFlags = args.installFlags;
16911        final String installerPackageName = args.installerPackageName;
16912        final String volumeUuid = args.volumeUuid;
16913        final File tmpPackageFile = new File(args.getCodePath());
16914        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16915        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16916                || (args.volumeUuid != null));
16917        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16918        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16919        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16920        final boolean virtualPreload =
16921                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16922        boolean replace = false;
16923        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16924        if (args.move != null) {
16925            // moving a complete application; perform an initial scan on the new install location
16926            scanFlags |= SCAN_INITIAL;
16927        }
16928        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16929            scanFlags |= SCAN_DONT_KILL_APP;
16930        }
16931        if (instantApp) {
16932            scanFlags |= SCAN_AS_INSTANT_APP;
16933        }
16934        if (fullApp) {
16935            scanFlags |= SCAN_AS_FULL_APP;
16936        }
16937        if (virtualPreload) {
16938            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16939        }
16940
16941        // Result object to be returned
16942        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16943        res.installerPackageName = installerPackageName;
16944
16945        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16946
16947        // Sanity check
16948        if (instantApp && (forwardLocked || onExternal)) {
16949            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16950                    + " external=" + onExternal);
16951            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16952            return;
16953        }
16954
16955        // Retrieve PackageSettings and parse package
16956        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16957                | PackageParser.PARSE_ENFORCE_CODE
16958                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16959                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16960                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16961        PackageParser pp = new PackageParser();
16962        pp.setSeparateProcesses(mSeparateProcesses);
16963        pp.setDisplayMetrics(mMetrics);
16964        pp.setCallback(mPackageParserCallback);
16965
16966        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16967        final PackageParser.Package pkg;
16968        try {
16969            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16970            DexMetadataHelper.validatePackageDexMetadata(pkg);
16971        } catch (PackageParserException e) {
16972            res.setError("Failed parse during installPackageLI", e);
16973            return;
16974        } finally {
16975            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16976        }
16977
16978        // Instant apps have several additional install-time checks.
16979        if (instantApp) {
16980            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16981                Slog.w(TAG,
16982                        "Instant app package " + pkg.packageName + " does not target at least O");
16983                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16984                        "Instant app package must target at least O");
16985                return;
16986            }
16987            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16988                Slog.w(TAG, "Instant app package " + pkg.packageName
16989                        + " does not target targetSandboxVersion 2");
16990                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16991                        "Instant app package must use targetSandboxVersion 2");
16992                return;
16993            }
16994            if (pkg.mSharedUserId != null) {
16995                Slog.w(TAG, "Instant app package " + pkg.packageName
16996                        + " may not declare sharedUserId.");
16997                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16998                        "Instant app package may not declare a sharedUserId");
16999                return;
17000            }
17001        }
17002
17003        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17004            // Static shared libraries have synthetic package names
17005            renameStaticSharedLibraryPackage(pkg);
17006
17007            // No static shared libs on external storage
17008            if (onExternal) {
17009                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17010                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17011                        "Packages declaring static-shared libs cannot be updated");
17012                return;
17013            }
17014        }
17015
17016        // If we are installing a clustered package add results for the children
17017        if (pkg.childPackages != null) {
17018            synchronized (mPackages) {
17019                final int childCount = pkg.childPackages.size();
17020                for (int i = 0; i < childCount; i++) {
17021                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17022                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17023                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17024                    childRes.pkg = childPkg;
17025                    childRes.name = childPkg.packageName;
17026                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17027                    if (childPs != null) {
17028                        childRes.origUsers = childPs.queryInstalledUsers(
17029                                sUserManager.getUserIds(), true);
17030                    }
17031                    if ((mPackages.containsKey(childPkg.packageName))) {
17032                        childRes.removedInfo = new PackageRemovedInfo(this);
17033                        childRes.removedInfo.removedPackage = childPkg.packageName;
17034                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17035                    }
17036                    if (res.addedChildPackages == null) {
17037                        res.addedChildPackages = new ArrayMap<>();
17038                    }
17039                    res.addedChildPackages.put(childPkg.packageName, childRes);
17040                }
17041            }
17042        }
17043
17044        // If package doesn't declare API override, mark that we have an install
17045        // time CPU ABI override.
17046        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17047            pkg.cpuAbiOverride = args.abiOverride;
17048        }
17049
17050        String pkgName = res.name = pkg.packageName;
17051        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17052            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17053                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17054                return;
17055            }
17056        }
17057
17058        try {
17059            // either use what we've been given or parse directly from the APK
17060            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17061                pkg.setSigningDetails(args.signingDetails);
17062            } else {
17063                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17064            }
17065        } catch (PackageParserException e) {
17066            res.setError("Failed collect during installPackageLI", e);
17067            return;
17068        }
17069
17070        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17071                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17072            Slog.w(TAG, "Instant app package " + pkg.packageName
17073                    + " is not signed with at least APK Signature Scheme v2");
17074            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17075                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17076            return;
17077        }
17078
17079        // Get rid of all references to package scan path via parser.
17080        pp = null;
17081        String oldCodePath = null;
17082        boolean systemApp = false;
17083        synchronized (mPackages) {
17084            // Check if installing already existing package
17085            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17086                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17087                if (pkg.mOriginalPackages != null
17088                        && pkg.mOriginalPackages.contains(oldName)
17089                        && mPackages.containsKey(oldName)) {
17090                    // This package is derived from an original package,
17091                    // and this device has been updating from that original
17092                    // name.  We must continue using the original name, so
17093                    // rename the new package here.
17094                    pkg.setPackageName(oldName);
17095                    pkgName = pkg.packageName;
17096                    replace = true;
17097                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17098                            + oldName + " pkgName=" + pkgName);
17099                } else if (mPackages.containsKey(pkgName)) {
17100                    // This package, under its official name, already exists
17101                    // on the device; we should replace it.
17102                    replace = true;
17103                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17104                }
17105
17106                // Child packages are installed through the parent package
17107                if (pkg.parentPackage != null) {
17108                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17109                            "Package " + pkg.packageName + " is child of package "
17110                                    + pkg.parentPackage.parentPackage + ". Child packages "
17111                                    + "can be updated only through the parent package.");
17112                    return;
17113                }
17114
17115                if (replace) {
17116                    // Prevent apps opting out from runtime permissions
17117                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17118                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17119                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17120                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17121                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17122                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17123                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17124                                        + " doesn't support runtime permissions but the old"
17125                                        + " target SDK " + oldTargetSdk + " does.");
17126                        return;
17127                    }
17128                    // Prevent persistent apps from being updated
17129                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17130                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17131                                "Package " + oldPackage.packageName + " is a persistent app. "
17132                                        + "Persistent apps are not updateable.");
17133                        return;
17134                    }
17135                    // Prevent apps from downgrading their targetSandbox.
17136                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17137                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17138                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17139                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17140                                "Package " + pkg.packageName + " new target sandbox "
17141                                + newTargetSandbox + " is incompatible with the previous value of"
17142                                + oldTargetSandbox + ".");
17143                        return;
17144                    }
17145
17146                    // Prevent installing of child packages
17147                    if (oldPackage.parentPackage != null) {
17148                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17149                                "Package " + pkg.packageName + " is child of package "
17150                                        + oldPackage.parentPackage + ". Child packages "
17151                                        + "can be updated only through the parent package.");
17152                        return;
17153                    }
17154                }
17155            }
17156
17157            PackageSetting ps = mSettings.mPackages.get(pkgName);
17158            if (ps != null) {
17159                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17160
17161                // Static shared libs have same package with different versions where
17162                // we internally use a synthetic package name to allow multiple versions
17163                // of the same package, therefore we need to compare signatures against
17164                // the package setting for the latest library version.
17165                PackageSetting signatureCheckPs = ps;
17166                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17167                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17168                    if (libraryEntry != null) {
17169                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17170                    }
17171                }
17172
17173                // Quick sanity check that we're signed correctly if updating;
17174                // we'll check this again later when scanning, but we want to
17175                // bail early here before tripping over redefined permissions.
17176                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17177                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17178                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17179                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17180                                + pkg.packageName + " upgrade keys do not match the "
17181                                + "previously installed version");
17182                        return;
17183                    }
17184                } else {
17185                    try {
17186                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17187                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17188                        // We don't care about disabledPkgSetting on install for now.
17189                        final boolean compatMatch = verifySignatures(
17190                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17191                                compareRecover);
17192                        // The new KeySets will be re-added later in the scanning process.
17193                        if (compatMatch) {
17194                            synchronized (mPackages) {
17195                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17196                            }
17197                        }
17198                    } catch (PackageManagerException e) {
17199                        res.setError(e.error, e.getMessage());
17200                        return;
17201                    }
17202                }
17203
17204                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17205                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17206                    systemApp = (ps.pkg.applicationInfo.flags &
17207                            ApplicationInfo.FLAG_SYSTEM) != 0;
17208                }
17209                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17210            }
17211
17212            int N = pkg.permissions.size();
17213            for (int i = N-1; i >= 0; i--) {
17214                final PackageParser.Permission perm = pkg.permissions.get(i);
17215                final BasePermission bp =
17216                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17217
17218                // Don't allow anyone but the system to define ephemeral permissions.
17219                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17220                        && !systemApp) {
17221                    Slog.w(TAG, "Non-System package " + pkg.packageName
17222                            + " attempting to delcare ephemeral permission "
17223                            + perm.info.name + "; Removing ephemeral.");
17224                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17225                }
17226
17227                // Check whether the newly-scanned package wants to define an already-defined perm
17228                if (bp != null) {
17229                    // If the defining package is signed with our cert, it's okay.  This
17230                    // also includes the "updating the same package" case, of course.
17231                    // "updating same package" could also involve key-rotation.
17232                    final boolean sigsOk;
17233                    final String sourcePackageName = bp.getSourcePackageName();
17234                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17235                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17236                    if (sourcePackageName.equals(pkg.packageName)
17237                            && (ksms.shouldCheckUpgradeKeySetLocked(
17238                                    sourcePackageSetting, scanFlags))) {
17239                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17240                    } else {
17241
17242                        // in the event of signing certificate rotation, we need to see if the
17243                        // package's certificate has rotated from the current one, or if it is an
17244                        // older certificate with which the current is ok with sharing permissions
17245                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17246                                        pkg.mSigningDetails,
17247                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17248                            sigsOk = true;
17249                        } else if (pkg.mSigningDetails.checkCapability(
17250                                        sourcePackageSetting.signatures.mSigningDetails,
17251                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17252
17253                            // the scanned package checks out, has signing certificate rotation
17254                            // history, and is newer; bring it over
17255                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17256                            sigsOk = true;
17257                        } else {
17258                            sigsOk = false;
17259                        }
17260                    }
17261                    if (!sigsOk) {
17262                        // If the owning package is the system itself, we log but allow
17263                        // install to proceed; we fail the install on all other permission
17264                        // redefinitions.
17265                        if (!sourcePackageName.equals("android")) {
17266                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17267                                    + pkg.packageName + " attempting to redeclare permission "
17268                                    + perm.info.name + " already owned by " + sourcePackageName);
17269                            res.origPermission = perm.info.name;
17270                            res.origPackage = sourcePackageName;
17271                            return;
17272                        } else {
17273                            Slog.w(TAG, "Package " + pkg.packageName
17274                                    + " attempting to redeclare system permission "
17275                                    + perm.info.name + "; ignoring new declaration");
17276                            pkg.permissions.remove(i);
17277                        }
17278                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17279                        // Prevent apps to change protection level to dangerous from any other
17280                        // type as this would allow a privilege escalation where an app adds a
17281                        // normal/signature permission in other app's group and later redefines
17282                        // it as dangerous leading to the group auto-grant.
17283                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17284                                == PermissionInfo.PROTECTION_DANGEROUS) {
17285                            if (bp != null && !bp.isRuntime()) {
17286                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17287                                        + "non-runtime permission " + perm.info.name
17288                                        + " to runtime; keeping old protection level");
17289                                perm.info.protectionLevel = bp.getProtectionLevel();
17290                            }
17291                        }
17292                    }
17293                }
17294            }
17295        }
17296
17297        if (systemApp) {
17298            if (onExternal) {
17299                // Abort update; system app can't be replaced with app on sdcard
17300                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17301                        "Cannot install updates to system apps on sdcard");
17302                return;
17303            } else if (instantApp) {
17304                // Abort update; system app can't be replaced with an instant app
17305                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17306                        "Cannot update a system app with an instant app");
17307                return;
17308            }
17309        }
17310
17311        if (args.move != null) {
17312            // We did an in-place move, so dex is ready to roll
17313            scanFlags |= SCAN_NO_DEX;
17314            scanFlags |= SCAN_MOVE;
17315
17316            synchronized (mPackages) {
17317                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17318                if (ps == null) {
17319                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17320                            "Missing settings for moved package " + pkgName);
17321                }
17322
17323                // We moved the entire application as-is, so bring over the
17324                // previously derived ABI information.
17325                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17326                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17327            }
17328
17329        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17330            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17331            scanFlags |= SCAN_NO_DEX;
17332
17333            try {
17334                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17335                    args.abiOverride : pkg.cpuAbiOverride);
17336                final boolean extractNativeLibs = !pkg.isLibrary();
17337                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17338            } catch (PackageManagerException pme) {
17339                Slog.e(TAG, "Error deriving application ABI", pme);
17340                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17341                return;
17342            }
17343
17344            // Shared libraries for the package need to be updated.
17345            synchronized (mPackages) {
17346                try {
17347                    updateSharedLibrariesLPr(pkg, null);
17348                } catch (PackageManagerException e) {
17349                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17350                }
17351            }
17352        }
17353
17354        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17355            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17356            return;
17357        }
17358
17359        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17360            String apkPath = null;
17361            synchronized (mPackages) {
17362                // Note that if the attacker managed to skip verify setup, for example by tampering
17363                // with the package settings, upon reboot we will do full apk verification when
17364                // verity is not detected.
17365                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17366                if (ps != null && ps.isPrivileged()) {
17367                    apkPath = pkg.baseCodePath;
17368                }
17369            }
17370
17371            if (apkPath != null) {
17372                final VerityUtils.SetupResult result =
17373                        VerityUtils.generateApkVeritySetupData(apkPath);
17374                if (result.isOk()) {
17375                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17376                    FileDescriptor fd = result.getUnownedFileDescriptor();
17377                    try {
17378                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17379                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17380                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17381                    } catch (InstallerException | IOException | DigestException |
17382                             NoSuchAlgorithmException e) {
17383                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17384                                "Failed to set up verity: " + e);
17385                        return;
17386                    } finally {
17387                        IoUtils.closeQuietly(fd);
17388                    }
17389                } else if (result.isFailed()) {
17390                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17391                    return;
17392                } else {
17393                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17394                    // reboot.
17395                }
17396            }
17397        }
17398
17399        if (!instantApp) {
17400            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17401        } else {
17402            if (DEBUG_DOMAIN_VERIFICATION) {
17403                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17404            }
17405        }
17406
17407        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17408                "installPackageLI")) {
17409            if (replace) {
17410                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17411                    // Static libs have a synthetic package name containing the version
17412                    // and cannot be updated as an update would get a new package name,
17413                    // unless this is the exact same version code which is useful for
17414                    // development.
17415                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17416                    if (existingPkg != null &&
17417                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17418                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17419                                + "static-shared libs cannot be updated");
17420                        return;
17421                    }
17422                }
17423                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17424                        installerPackageName, res, args.installReason);
17425            } else {
17426                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17427                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17428            }
17429        }
17430
17431        // Prepare the application profiles for the new code paths.
17432        // This needs to be done before invoking dexopt so that any install-time profile
17433        // can be used for optimizations.
17434        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17435
17436        // Check whether we need to dexopt the app.
17437        //
17438        // NOTE: it is IMPORTANT to call dexopt:
17439        //   - after doRename which will sync the package data from PackageParser.Package and its
17440        //     corresponding ApplicationInfo.
17441        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17442        //     uid of the application (pkg.applicationInfo.uid).
17443        //     This update happens in place!
17444        //
17445        // We only need to dexopt if the package meets ALL of the following conditions:
17446        //   1) it is not forward locked.
17447        //   2) it is not on on an external ASEC container.
17448        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17449        //   4) it is not debuggable.
17450        //
17451        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17452        // complete, so we skip this step during installation. Instead, we'll take extra time
17453        // the first time the instant app starts. It's preferred to do it this way to provide
17454        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17455        // middle of running an instant app. The default behaviour can be overridden
17456        // via gservices.
17457        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17458                && !forwardLocked
17459                && !pkg.applicationInfo.isExternalAsec()
17460                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17461                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17462                && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17463
17464        if (performDexopt) {
17465            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17466            // Do not run PackageDexOptimizer through the local performDexOpt
17467            // method because `pkg` may not be in `mPackages` yet.
17468            //
17469            // Also, don't fail application installs if the dexopt step fails.
17470            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17471                    REASON_INSTALL,
17472                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17473                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17474            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17475                    null /* instructionSets */,
17476                    getOrCreateCompilerPackageStats(pkg),
17477                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17478                    dexoptOptions);
17479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17480        }
17481
17482        // Notify BackgroundDexOptService that the package has been changed.
17483        // If this is an update of a package which used to fail to compile,
17484        // BackgroundDexOptService will remove it from its blacklist.
17485        // TODO: Layering violation
17486        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17487
17488        synchronized (mPackages) {
17489            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17490            if (ps != null) {
17491                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17492                ps.setUpdateAvailable(false /*updateAvailable*/);
17493            }
17494
17495            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17496            for (int i = 0; i < childCount; i++) {
17497                PackageParser.Package childPkg = pkg.childPackages.get(i);
17498                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17499                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17500                if (childPs != null) {
17501                    childRes.newUsers = childPs.queryInstalledUsers(
17502                            sUserManager.getUserIds(), true);
17503                }
17504            }
17505
17506            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17507                updateSequenceNumberLP(ps, res.newUsers);
17508                updateInstantAppInstallerLocked(pkgName);
17509            }
17510        }
17511    }
17512
17513    private void startIntentFilterVerifications(int userId, boolean replacing,
17514            PackageParser.Package pkg) {
17515        if (mIntentFilterVerifierComponent == null) {
17516            Slog.w(TAG, "No IntentFilter verification will not be done as "
17517                    + "there is no IntentFilterVerifier available!");
17518            return;
17519        }
17520
17521        final int verifierUid = getPackageUid(
17522                mIntentFilterVerifierComponent.getPackageName(),
17523                MATCH_DEBUG_TRIAGED_MISSING,
17524                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17525
17526        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17527        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17528        mHandler.sendMessage(msg);
17529
17530        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17531        for (int i = 0; i < childCount; i++) {
17532            PackageParser.Package childPkg = pkg.childPackages.get(i);
17533            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17534            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17535            mHandler.sendMessage(msg);
17536        }
17537    }
17538
17539    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17540            PackageParser.Package pkg) {
17541        int size = pkg.activities.size();
17542        if (size == 0) {
17543            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17544                    "No activity, so no need to verify any IntentFilter!");
17545            return;
17546        }
17547
17548        final boolean hasDomainURLs = hasDomainURLs(pkg);
17549        if (!hasDomainURLs) {
17550            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17551                    "No domain URLs, so no need to verify any IntentFilter!");
17552            return;
17553        }
17554
17555        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17556                + " if any IntentFilter from the " + size
17557                + " Activities needs verification ...");
17558
17559        int count = 0;
17560        final String packageName = pkg.packageName;
17561
17562        synchronized (mPackages) {
17563            // If this is a new install and we see that we've already run verification for this
17564            // package, we have nothing to do: it means the state was restored from backup.
17565            if (!replacing) {
17566                IntentFilterVerificationInfo ivi =
17567                        mSettings.getIntentFilterVerificationLPr(packageName);
17568                if (ivi != null) {
17569                    if (DEBUG_DOMAIN_VERIFICATION) {
17570                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17571                                + ivi.getStatusString());
17572                    }
17573                    return;
17574                }
17575            }
17576
17577            // If any filters need to be verified, then all need to be.
17578            boolean needToVerify = false;
17579            for (PackageParser.Activity a : pkg.activities) {
17580                for (ActivityIntentInfo filter : a.intents) {
17581                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17582                        if (DEBUG_DOMAIN_VERIFICATION) {
17583                            Slog.d(TAG,
17584                                    "Intent filter needs verification, so processing all filters");
17585                        }
17586                        needToVerify = true;
17587                        break;
17588                    }
17589                }
17590            }
17591
17592            if (needToVerify) {
17593                final int verificationId = mIntentFilterVerificationToken++;
17594                for (PackageParser.Activity a : pkg.activities) {
17595                    for (ActivityIntentInfo filter : a.intents) {
17596                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17597                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17598                                    "Verification needed for IntentFilter:" + filter.toString());
17599                            mIntentFilterVerifier.addOneIntentFilterVerification(
17600                                    verifierUid, userId, verificationId, filter, packageName);
17601                            count++;
17602                        }
17603                    }
17604                }
17605            }
17606        }
17607
17608        if (count > 0) {
17609            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17610                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17611                    +  " for userId:" + userId);
17612            mIntentFilterVerifier.startVerifications(userId);
17613        } else {
17614            if (DEBUG_DOMAIN_VERIFICATION) {
17615                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17616            }
17617        }
17618    }
17619
17620    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17621        final ComponentName cn  = filter.activity.getComponentName();
17622        final String packageName = cn.getPackageName();
17623
17624        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17625                packageName);
17626        if (ivi == null) {
17627            return true;
17628        }
17629        int status = ivi.getStatus();
17630        switch (status) {
17631            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17632            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17633                return true;
17634
17635            default:
17636                // Nothing to do
17637                return false;
17638        }
17639    }
17640
17641    private static boolean isMultiArch(ApplicationInfo info) {
17642        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17643    }
17644
17645    private static boolean isExternal(PackageParser.Package pkg) {
17646        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17647    }
17648
17649    private static boolean isExternal(PackageSetting ps) {
17650        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17651    }
17652
17653    private static boolean isSystemApp(PackageParser.Package pkg) {
17654        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17655    }
17656
17657    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17658        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17659    }
17660
17661    private static boolean isOemApp(PackageParser.Package pkg) {
17662        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17663    }
17664
17665    private static boolean isVendorApp(PackageParser.Package pkg) {
17666        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17667    }
17668
17669    private static boolean isProductApp(PackageParser.Package pkg) {
17670        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17671    }
17672
17673    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17674        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17675    }
17676
17677    private static boolean isSystemApp(PackageSetting ps) {
17678        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17679    }
17680
17681    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17682        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17683    }
17684
17685    private int packageFlagsToInstallFlags(PackageSetting ps) {
17686        int installFlags = 0;
17687        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17688            // This existing package was an external ASEC install when we have
17689            // the external flag without a UUID
17690            installFlags |= PackageManager.INSTALL_EXTERNAL;
17691        }
17692        if (ps.isForwardLocked()) {
17693            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17694        }
17695        return installFlags;
17696    }
17697
17698    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17699        if (isExternal(pkg)) {
17700            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17701                return mSettings.getExternalVersion();
17702            } else {
17703                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17704            }
17705        } else {
17706            return mSettings.getInternalVersion();
17707        }
17708    }
17709
17710    private void deleteTempPackageFiles() {
17711        final FilenameFilter filter = new FilenameFilter() {
17712            public boolean accept(File dir, String name) {
17713                return name.startsWith("vmdl") && name.endsWith(".tmp");
17714            }
17715        };
17716        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17717            file.delete();
17718        }
17719    }
17720
17721    @Override
17722    public void deletePackageAsUser(String packageName, int versionCode,
17723            IPackageDeleteObserver observer, int userId, int flags) {
17724        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17725                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17726    }
17727
17728    @Override
17729    public void deletePackageVersioned(VersionedPackage versionedPackage,
17730            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17731        final int callingUid = Binder.getCallingUid();
17732        mContext.enforceCallingOrSelfPermission(
17733                android.Manifest.permission.DELETE_PACKAGES, null);
17734        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17735        Preconditions.checkNotNull(versionedPackage);
17736        Preconditions.checkNotNull(observer);
17737        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17738                PackageManager.VERSION_CODE_HIGHEST,
17739                Long.MAX_VALUE, "versionCode must be >= -1");
17740
17741        final String packageName = versionedPackage.getPackageName();
17742        final long versionCode = versionedPackage.getLongVersionCode();
17743        final String internalPackageName;
17744        synchronized (mPackages) {
17745            // Normalize package name to handle renamed packages and static libs
17746            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17747        }
17748
17749        final int uid = Binder.getCallingUid();
17750        if (!isOrphaned(internalPackageName)
17751                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17752            try {
17753                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17754                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17755                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17756                observer.onUserActionRequired(intent);
17757            } catch (RemoteException re) {
17758            }
17759            return;
17760        }
17761        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17762        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17763        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17764            mContext.enforceCallingOrSelfPermission(
17765                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17766                    "deletePackage for user " + userId);
17767        }
17768
17769        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17770            try {
17771                observer.onPackageDeleted(packageName,
17772                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17773            } catch (RemoteException re) {
17774            }
17775            return;
17776        }
17777
17778        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17779            try {
17780                observer.onPackageDeleted(packageName,
17781                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17782            } catch (RemoteException re) {
17783            }
17784            return;
17785        }
17786
17787        if (DEBUG_REMOVE) {
17788            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17789                    + " deleteAllUsers: " + deleteAllUsers + " version="
17790                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17791                    ? "VERSION_CODE_HIGHEST" : versionCode));
17792        }
17793        // Queue up an async operation since the package deletion may take a little while.
17794        mHandler.post(new Runnable() {
17795            public void run() {
17796                mHandler.removeCallbacks(this);
17797                int returnCode;
17798                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17799                boolean doDeletePackage = true;
17800                if (ps != null) {
17801                    final boolean targetIsInstantApp =
17802                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17803                    doDeletePackage = !targetIsInstantApp
17804                            || canViewInstantApps;
17805                }
17806                if (doDeletePackage) {
17807                    if (!deleteAllUsers) {
17808                        returnCode = deletePackageX(internalPackageName, versionCode,
17809                                userId, deleteFlags);
17810                    } else {
17811                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17812                                internalPackageName, users);
17813                        // If nobody is blocking uninstall, proceed with delete for all users
17814                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17815                            returnCode = deletePackageX(internalPackageName, versionCode,
17816                                    userId, deleteFlags);
17817                        } else {
17818                            // Otherwise uninstall individually for users with blockUninstalls=false
17819                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17820                            for (int userId : users) {
17821                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17822                                    returnCode = deletePackageX(internalPackageName, versionCode,
17823                                            userId, userFlags);
17824                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17825                                        Slog.w(TAG, "Package delete failed for user " + userId
17826                                                + ", returnCode " + returnCode);
17827                                    }
17828                                }
17829                            }
17830                            // The app has only been marked uninstalled for certain users.
17831                            // We still need to report that delete was blocked
17832                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17833                        }
17834                    }
17835                } else {
17836                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17837                }
17838                try {
17839                    observer.onPackageDeleted(packageName, returnCode, null);
17840                } catch (RemoteException e) {
17841                    Log.i(TAG, "Observer no longer exists.");
17842                } //end catch
17843            } //end run
17844        });
17845    }
17846
17847    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17848        if (pkg.staticSharedLibName != null) {
17849            return pkg.manifestPackageName;
17850        }
17851        return pkg.packageName;
17852    }
17853
17854    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17855        // Handle renamed packages
17856        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17857        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17858
17859        // Is this a static library?
17860        LongSparseArray<SharedLibraryEntry> versionedLib =
17861                mStaticLibsByDeclaringPackage.get(packageName);
17862        if (versionedLib == null || versionedLib.size() <= 0) {
17863            return packageName;
17864        }
17865
17866        // Figure out which lib versions the caller can see
17867        LongSparseLongArray versionsCallerCanSee = null;
17868        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17869        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17870                && callingAppId != Process.ROOT_UID) {
17871            versionsCallerCanSee = new LongSparseLongArray();
17872            String libName = versionedLib.valueAt(0).info.getName();
17873            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17874            if (uidPackages != null) {
17875                for (String uidPackage : uidPackages) {
17876                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17877                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17878                    if (libIdx >= 0) {
17879                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17880                        versionsCallerCanSee.append(libVersion, libVersion);
17881                    }
17882                }
17883            }
17884        }
17885
17886        // Caller can see nothing - done
17887        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17888            return packageName;
17889        }
17890
17891        // Find the version the caller can see and the app version code
17892        SharedLibraryEntry highestVersion = null;
17893        final int versionCount = versionedLib.size();
17894        for (int i = 0; i < versionCount; i++) {
17895            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17896            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17897                    libEntry.info.getLongVersion()) < 0) {
17898                continue;
17899            }
17900            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17901            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17902                if (libVersionCode == versionCode) {
17903                    return libEntry.apk;
17904                }
17905            } else if (highestVersion == null) {
17906                highestVersion = libEntry;
17907            } else if (libVersionCode  > highestVersion.info
17908                    .getDeclaringPackage().getLongVersionCode()) {
17909                highestVersion = libEntry;
17910            }
17911        }
17912
17913        if (highestVersion != null) {
17914            return highestVersion.apk;
17915        }
17916
17917        return packageName;
17918    }
17919
17920    boolean isCallerVerifier(int callingUid) {
17921        final int callingUserId = UserHandle.getUserId(callingUid);
17922        return mRequiredVerifierPackage != null &&
17923                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17924    }
17925
17926    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17927        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17928              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17929            return true;
17930        }
17931        final int callingUserId = UserHandle.getUserId(callingUid);
17932        // If the caller installed the pkgName, then allow it to silently uninstall.
17933        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17934            return true;
17935        }
17936
17937        // Allow package verifier to silently uninstall.
17938        if (mRequiredVerifierPackage != null &&
17939                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17940            return true;
17941        }
17942
17943        // Allow package uninstaller to silently uninstall.
17944        if (mRequiredUninstallerPackage != null &&
17945                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17946            return true;
17947        }
17948
17949        // Allow storage manager to silently uninstall.
17950        if (mStorageManagerPackage != null &&
17951                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17952            return true;
17953        }
17954
17955        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17956        // uninstall for device owner provisioning.
17957        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17958                == PERMISSION_GRANTED) {
17959            return true;
17960        }
17961
17962        return false;
17963    }
17964
17965    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17966        int[] result = EMPTY_INT_ARRAY;
17967        for (int userId : userIds) {
17968            if (getBlockUninstallForUser(packageName, userId)) {
17969                result = ArrayUtils.appendInt(result, userId);
17970            }
17971        }
17972        return result;
17973    }
17974
17975    @Override
17976    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17977        final int callingUid = Binder.getCallingUid();
17978        if (getInstantAppPackageName(callingUid) != null
17979                && !isCallerSameApp(packageName, callingUid)) {
17980            return false;
17981        }
17982        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17983    }
17984
17985    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17986        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17987                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17988        try {
17989            if (dpm != null) {
17990                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17991                        /* callingUserOnly =*/ false);
17992                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17993                        : deviceOwnerComponentName.getPackageName();
17994                // Does the package contains the device owner?
17995                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17996                // this check is probably not needed, since DO should be registered as a device
17997                // admin on some user too. (Original bug for this: b/17657954)
17998                if (packageName.equals(deviceOwnerPackageName)) {
17999                    return true;
18000                }
18001                // Does it contain a device admin for any user?
18002                int[] users;
18003                if (userId == UserHandle.USER_ALL) {
18004                    users = sUserManager.getUserIds();
18005                } else {
18006                    users = new int[]{userId};
18007                }
18008                for (int i = 0; i < users.length; ++i) {
18009                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18010                        return true;
18011                    }
18012                }
18013            }
18014        } catch (RemoteException e) {
18015        }
18016        return false;
18017    }
18018
18019    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18020        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18021    }
18022
18023    /**
18024     *  This method is an internal method that could be get invoked either
18025     *  to delete an installed package or to clean up a failed installation.
18026     *  After deleting an installed package, a broadcast is sent to notify any
18027     *  listeners that the package has been removed. For cleaning up a failed
18028     *  installation, the broadcast is not necessary since the package's
18029     *  installation wouldn't have sent the initial broadcast either
18030     *  The key steps in deleting a package are
18031     *  deleting the package information in internal structures like mPackages,
18032     *  deleting the packages base directories through installd
18033     *  updating mSettings to reflect current status
18034     *  persisting settings for later use
18035     *  sending a broadcast if necessary
18036     */
18037    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18038        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18039        final boolean res;
18040
18041        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18042                ? UserHandle.USER_ALL : userId;
18043
18044        if (isPackageDeviceAdmin(packageName, removeUser)) {
18045            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18046            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18047        }
18048
18049        PackageSetting uninstalledPs = null;
18050        PackageParser.Package pkg = null;
18051
18052        // for the uninstall-updates case and restricted profiles, remember the per-
18053        // user handle installed state
18054        int[] allUsers;
18055        synchronized (mPackages) {
18056            uninstalledPs = mSettings.mPackages.get(packageName);
18057            if (uninstalledPs == null) {
18058                Slog.w(TAG, "Not removing non-existent package " + packageName);
18059                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18060            }
18061
18062            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18063                    && uninstalledPs.versionCode != versionCode) {
18064                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18065                        + uninstalledPs.versionCode + " != " + versionCode);
18066                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18067            }
18068
18069            // Static shared libs can be declared by any package, so let us not
18070            // allow removing a package if it provides a lib others depend on.
18071            pkg = mPackages.get(packageName);
18072
18073            allUsers = sUserManager.getUserIds();
18074
18075            if (pkg != null && pkg.staticSharedLibName != null) {
18076                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18077                        pkg.staticSharedLibVersion);
18078                if (libEntry != null) {
18079                    for (int currUserId : allUsers) {
18080                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18081                            continue;
18082                        }
18083                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18084                                libEntry.info, 0, currUserId);
18085                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18086                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18087                                    + " hosting lib " + libEntry.info.getName() + " version "
18088                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18089                                    + " for user " + currUserId);
18090                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18091                        }
18092                    }
18093                }
18094            }
18095
18096            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18097        }
18098
18099        final int freezeUser;
18100        if (isUpdatedSystemApp(uninstalledPs)
18101                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18102            // We're downgrading a system app, which will apply to all users, so
18103            // freeze them all during the downgrade
18104            freezeUser = UserHandle.USER_ALL;
18105        } else {
18106            freezeUser = removeUser;
18107        }
18108
18109        synchronized (mInstallLock) {
18110            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18111            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18112                    deleteFlags, "deletePackageX")) {
18113                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18114                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18115            }
18116            synchronized (mPackages) {
18117                if (res) {
18118                    if (pkg != null) {
18119                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18120                    }
18121                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18122                    updateInstantAppInstallerLocked(packageName);
18123                }
18124            }
18125        }
18126
18127        if (res) {
18128            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18129            info.sendPackageRemovedBroadcasts(killApp);
18130            info.sendSystemPackageUpdatedBroadcasts();
18131            info.sendSystemPackageAppearedBroadcasts();
18132        }
18133        // Force a gc here.
18134        Runtime.getRuntime().gc();
18135        // Delete the resources here after sending the broadcast to let
18136        // other processes clean up before deleting resources.
18137        if (info.args != null) {
18138            synchronized (mInstallLock) {
18139                info.args.doPostDeleteLI(true);
18140            }
18141        }
18142
18143        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18144    }
18145
18146    static class PackageRemovedInfo {
18147        final PackageSender packageSender;
18148        String removedPackage;
18149        String installerPackageName;
18150        int uid = -1;
18151        int removedAppId = -1;
18152        int[] origUsers;
18153        int[] removedUsers = null;
18154        int[] broadcastUsers = null;
18155        int[] instantUserIds = null;
18156        SparseArray<Integer> installReasons;
18157        boolean isRemovedPackageSystemUpdate = false;
18158        boolean isUpdate;
18159        boolean dataRemoved;
18160        boolean removedForAllUsers;
18161        boolean isStaticSharedLib;
18162        // Clean up resources deleted packages.
18163        InstallArgs args = null;
18164        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18165        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18166
18167        PackageRemovedInfo(PackageSender packageSender) {
18168            this.packageSender = packageSender;
18169        }
18170
18171        void sendPackageRemovedBroadcasts(boolean killApp) {
18172            sendPackageRemovedBroadcastInternal(killApp);
18173            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18174            for (int i = 0; i < childCount; i++) {
18175                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18176                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18177            }
18178        }
18179
18180        void sendSystemPackageUpdatedBroadcasts() {
18181            if (isRemovedPackageSystemUpdate) {
18182                sendSystemPackageUpdatedBroadcastsInternal();
18183                final int childCount = (removedChildPackages != null)
18184                        ? removedChildPackages.size() : 0;
18185                for (int i = 0; i < childCount; i++) {
18186                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18187                    if (childInfo.isRemovedPackageSystemUpdate) {
18188                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18189                    }
18190                }
18191            }
18192        }
18193
18194        void sendSystemPackageAppearedBroadcasts() {
18195            final int packageCount = (appearedChildPackages != null)
18196                    ? appearedChildPackages.size() : 0;
18197            for (int i = 0; i < packageCount; i++) {
18198                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18199                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18200                    true /*sendBootCompleted*/, false /*startReceiver*/,
18201                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18202            }
18203        }
18204
18205        private void sendSystemPackageUpdatedBroadcastsInternal() {
18206            Bundle extras = new Bundle(2);
18207            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18208            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18209            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18210                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18211            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18212                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18213            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18214                null, null, 0, removedPackage, null, null, null);
18215            if (installerPackageName != null) {
18216                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18217                        removedPackage, extras, 0 /*flags*/,
18218                        installerPackageName, null, null, null);
18219                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18220                        removedPackage, extras, 0 /*flags*/,
18221                        installerPackageName, null, null, null);
18222            }
18223        }
18224
18225        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18226            // Don't send static shared library removal broadcasts as these
18227            // libs are visible only the the apps that depend on them an one
18228            // cannot remove the library if it has a dependency.
18229            if (isStaticSharedLib) {
18230                return;
18231            }
18232            Bundle extras = new Bundle(2);
18233            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18234            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18235            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18236            if (isUpdate || isRemovedPackageSystemUpdate) {
18237                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18238            }
18239            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18240            if (removedPackage != null) {
18241                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18242                    removedPackage, extras, 0, null /*targetPackage*/, null,
18243                    broadcastUsers, instantUserIds);
18244                if (installerPackageName != null) {
18245                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18246                            removedPackage, extras, 0 /*flags*/,
18247                            installerPackageName, null, broadcastUsers, instantUserIds);
18248                }
18249                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18250                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18251                        removedPackage, extras,
18252                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18253                        null, null, broadcastUsers, instantUserIds);
18254                    packageSender.notifyPackageRemoved(removedPackage);
18255                }
18256            }
18257            if (removedAppId >= 0) {
18258                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18259                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18260                    null, null, broadcastUsers, instantUserIds);
18261            }
18262        }
18263
18264        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18265            removedUsers = userIds;
18266            if (removedUsers == null) {
18267                broadcastUsers = null;
18268                return;
18269            }
18270
18271            broadcastUsers = EMPTY_INT_ARRAY;
18272            instantUserIds = EMPTY_INT_ARRAY;
18273            for (int i = userIds.length - 1; i >= 0; --i) {
18274                final int userId = userIds[i];
18275                if (deletedPackageSetting.getInstantApp(userId)) {
18276                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18277                } else {
18278                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18279                }
18280            }
18281        }
18282    }
18283
18284    /*
18285     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18286     * flag is not set, the data directory is removed as well.
18287     * make sure this flag is set for partially installed apps. If not its meaningless to
18288     * delete a partially installed application.
18289     */
18290    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18291            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18292        String packageName = ps.name;
18293        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18294        // Retrieve object to delete permissions for shared user later on
18295        final PackageParser.Package deletedPkg;
18296        final PackageSetting deletedPs;
18297        // reader
18298        synchronized (mPackages) {
18299            deletedPkg = mPackages.get(packageName);
18300            deletedPs = mSettings.mPackages.get(packageName);
18301            if (outInfo != null) {
18302                outInfo.removedPackage = packageName;
18303                outInfo.installerPackageName = ps.installerPackageName;
18304                outInfo.isStaticSharedLib = deletedPkg != null
18305                        && deletedPkg.staticSharedLibName != null;
18306                outInfo.populateUsers(deletedPs == null ? null
18307                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18308            }
18309        }
18310
18311        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18312
18313        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18314            final PackageParser.Package resolvedPkg;
18315            if (deletedPkg != null) {
18316                resolvedPkg = deletedPkg;
18317            } else {
18318                // We don't have a parsed package when it lives on an ejected
18319                // adopted storage device, so fake something together
18320                resolvedPkg = new PackageParser.Package(ps.name);
18321                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18322            }
18323            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18324                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18325            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18326            if (outInfo != null) {
18327                outInfo.dataRemoved = true;
18328            }
18329            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18330        }
18331
18332        int removedAppId = -1;
18333
18334        // writer
18335        synchronized (mPackages) {
18336            boolean installedStateChanged = false;
18337            if (deletedPs != null) {
18338                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18339                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18340                    clearDefaultBrowserIfNeeded(packageName);
18341                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18342                    removedAppId = mSettings.removePackageLPw(packageName);
18343                    if (outInfo != null) {
18344                        outInfo.removedAppId = removedAppId;
18345                    }
18346                    mPermissionManager.updatePermissions(
18347                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18348                    if (deletedPs.sharedUser != null) {
18349                        // Remove permissions associated with package. Since runtime
18350                        // permissions are per user we have to kill the removed package
18351                        // or packages running under the shared user of the removed
18352                        // package if revoking the permissions requested only by the removed
18353                        // package is successful and this causes a change in gids.
18354                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18355                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18356                                    userId);
18357                            if (userIdToKill == UserHandle.USER_ALL
18358                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18359                                // If gids changed for this user, kill all affected packages.
18360                                mHandler.post(new Runnable() {
18361                                    @Override
18362                                    public void run() {
18363                                        // This has to happen with no lock held.
18364                                        killApplication(deletedPs.name, deletedPs.appId,
18365                                                KILL_APP_REASON_GIDS_CHANGED);
18366                                    }
18367                                });
18368                                break;
18369                            }
18370                        }
18371                    }
18372                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18373                }
18374                // make sure to preserve per-user disabled state if this removal was just
18375                // a downgrade of a system app to the factory package
18376                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18377                    if (DEBUG_REMOVE) {
18378                        Slog.d(TAG, "Propagating install state across downgrade");
18379                    }
18380                    for (int userId : allUserHandles) {
18381                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18382                        if (DEBUG_REMOVE) {
18383                            Slog.d(TAG, "    user " + userId + " => " + installed);
18384                        }
18385                        if (installed != ps.getInstalled(userId)) {
18386                            installedStateChanged = true;
18387                        }
18388                        ps.setInstalled(installed, userId);
18389                    }
18390                }
18391            }
18392            // can downgrade to reader
18393            if (writeSettings) {
18394                // Save settings now
18395                mSettings.writeLPr();
18396            }
18397            if (installedStateChanged) {
18398                mSettings.writeKernelMappingLPr(ps);
18399            }
18400        }
18401        if (removedAppId != -1) {
18402            // A user ID was deleted here. Go through all users and remove it
18403            // from KeyStore.
18404            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18405        }
18406    }
18407
18408    static boolean locationIsPrivileged(String path) {
18409        try {
18410            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18411            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18412            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18413            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18414            return path.startsWith(privilegedAppDir.getCanonicalPath())
18415                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18416                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18417                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18418        } catch (IOException e) {
18419            Slog.e(TAG, "Unable to access code path " + path);
18420        }
18421        return false;
18422    }
18423
18424    static boolean locationIsOem(String path) {
18425        try {
18426            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18427        } catch (IOException e) {
18428            Slog.e(TAG, "Unable to access code path " + path);
18429        }
18430        return false;
18431    }
18432
18433    static boolean locationIsVendor(String path) {
18434        try {
18435            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18436                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18437        } catch (IOException e) {
18438            Slog.e(TAG, "Unable to access code path " + path);
18439        }
18440        return false;
18441    }
18442
18443    static boolean locationIsProduct(String path) {
18444        try {
18445            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18446        } catch (IOException e) {
18447            Slog.e(TAG, "Unable to access code path " + path);
18448        }
18449        return false;
18450    }
18451
18452    /*
18453     * Tries to delete system package.
18454     */
18455    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18456            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18457            boolean writeSettings) {
18458        if (deletedPs.parentPackageName != null) {
18459            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18460            return false;
18461        }
18462
18463        final boolean applyUserRestrictions
18464                = (allUserHandles != null) && (outInfo.origUsers != null);
18465        final PackageSetting disabledPs;
18466        // Confirm if the system package has been updated
18467        // An updated system app can be deleted. This will also have to restore
18468        // the system pkg from system partition
18469        // reader
18470        synchronized (mPackages) {
18471            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18472        }
18473
18474        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18475                + " disabledPs=" + disabledPs);
18476
18477        if (disabledPs == null) {
18478            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18479            return false;
18480        } else if (DEBUG_REMOVE) {
18481            Slog.d(TAG, "Deleting system pkg from data partition");
18482        }
18483
18484        if (DEBUG_REMOVE) {
18485            if (applyUserRestrictions) {
18486                Slog.d(TAG, "Remembering install states:");
18487                for (int userId : allUserHandles) {
18488                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18489                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18490                }
18491            }
18492        }
18493
18494        // Delete the updated package
18495        outInfo.isRemovedPackageSystemUpdate = true;
18496        if (outInfo.removedChildPackages != null) {
18497            final int childCount = (deletedPs.childPackageNames != null)
18498                    ? deletedPs.childPackageNames.size() : 0;
18499            for (int i = 0; i < childCount; i++) {
18500                String childPackageName = deletedPs.childPackageNames.get(i);
18501                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18502                        .contains(childPackageName)) {
18503                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18504                            childPackageName);
18505                    if (childInfo != null) {
18506                        childInfo.isRemovedPackageSystemUpdate = true;
18507                    }
18508                }
18509            }
18510        }
18511
18512        if (disabledPs.versionCode < deletedPs.versionCode) {
18513            // Delete data for downgrades
18514            flags &= ~PackageManager.DELETE_KEEP_DATA;
18515        } else {
18516            // Preserve data by setting flag
18517            flags |= PackageManager.DELETE_KEEP_DATA;
18518        }
18519
18520        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18521                outInfo, writeSettings, disabledPs.pkg);
18522        if (!ret) {
18523            return false;
18524        }
18525
18526        // writer
18527        synchronized (mPackages) {
18528            // NOTE: The system package always needs to be enabled; even if it's for
18529            // a compressed stub. If we don't, installing the system package fails
18530            // during scan [scanning checks the disabled packages]. We will reverse
18531            // this later, after we've "installed" the stub.
18532            // Reinstate the old system package
18533            enableSystemPackageLPw(disabledPs.pkg);
18534            // Remove any native libraries from the upgraded package.
18535            removeNativeBinariesLI(deletedPs);
18536        }
18537
18538        // Install the system package
18539        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18540        try {
18541            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18542                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18543        } catch (PackageManagerException e) {
18544            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18545                    + e.getMessage());
18546            return false;
18547        } finally {
18548            if (disabledPs.pkg.isStub) {
18549                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18550            }
18551        }
18552        return true;
18553    }
18554
18555    /**
18556     * Installs a package that's already on the system partition.
18557     */
18558    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18559            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18560            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18561                    throws PackageManagerException {
18562        @ParseFlags int parseFlags =
18563                mDefParseFlags
18564                | PackageParser.PARSE_MUST_BE_APK
18565                | PackageParser.PARSE_IS_SYSTEM_DIR;
18566        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18567        if (isPrivileged || locationIsPrivileged(codePathString)) {
18568            scanFlags |= SCAN_AS_PRIVILEGED;
18569        }
18570        if (locationIsOem(codePathString)) {
18571            scanFlags |= SCAN_AS_OEM;
18572        }
18573        if (locationIsVendor(codePathString)) {
18574            scanFlags |= SCAN_AS_VENDOR;
18575        }
18576        if (locationIsProduct(codePathString)) {
18577            scanFlags |= SCAN_AS_PRODUCT;
18578        }
18579
18580        final File codePath = new File(codePathString);
18581        final PackageParser.Package pkg =
18582                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18583
18584        try {
18585            // update shared libraries for the newly re-installed system package
18586            updateSharedLibrariesLPr(pkg, null);
18587        } catch (PackageManagerException e) {
18588            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18589        }
18590
18591        prepareAppDataAfterInstallLIF(pkg);
18592
18593        // writer
18594        synchronized (mPackages) {
18595            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18596
18597            // Propagate the permissions state as we do not want to drop on the floor
18598            // runtime permissions. The update permissions method below will take
18599            // care of removing obsolete permissions and grant install permissions.
18600            if (origPermissionState != null) {
18601                ps.getPermissionsState().copyFrom(origPermissionState);
18602            }
18603            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18604                    mPermissionCallback);
18605
18606            final boolean applyUserRestrictions
18607                    = (allUserHandles != null) && (origUserHandles != null);
18608            if (applyUserRestrictions) {
18609                boolean installedStateChanged = false;
18610                if (DEBUG_REMOVE) {
18611                    Slog.d(TAG, "Propagating install state across reinstall");
18612                }
18613                for (int userId : allUserHandles) {
18614                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18615                    if (DEBUG_REMOVE) {
18616                        Slog.d(TAG, "    user " + userId + " => " + installed);
18617                    }
18618                    if (installed != ps.getInstalled(userId)) {
18619                        installedStateChanged = true;
18620                    }
18621                    ps.setInstalled(installed, userId);
18622
18623                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18624                }
18625                // Regardless of writeSettings we need to ensure that this restriction
18626                // state propagation is persisted
18627                mSettings.writeAllUsersPackageRestrictionsLPr();
18628                if (installedStateChanged) {
18629                    mSettings.writeKernelMappingLPr(ps);
18630                }
18631            }
18632            // can downgrade to reader here
18633            if (writeSettings) {
18634                mSettings.writeLPr();
18635            }
18636        }
18637        return pkg;
18638    }
18639
18640    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18641            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18642            PackageRemovedInfo outInfo, boolean writeSettings,
18643            PackageParser.Package replacingPackage) {
18644        synchronized (mPackages) {
18645            if (outInfo != null) {
18646                outInfo.uid = ps.appId;
18647            }
18648
18649            if (outInfo != null && outInfo.removedChildPackages != null) {
18650                final int childCount = (ps.childPackageNames != null)
18651                        ? ps.childPackageNames.size() : 0;
18652                for (int i = 0; i < childCount; i++) {
18653                    String childPackageName = ps.childPackageNames.get(i);
18654                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18655                    if (childPs == null) {
18656                        return false;
18657                    }
18658                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18659                            childPackageName);
18660                    if (childInfo != null) {
18661                        childInfo.uid = childPs.appId;
18662                    }
18663                }
18664            }
18665        }
18666
18667        // Delete package data from internal structures and also remove data if flag is set
18668        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18669
18670        // Delete the child packages data
18671        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18672        for (int i = 0; i < childCount; i++) {
18673            PackageSetting childPs;
18674            synchronized (mPackages) {
18675                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18676            }
18677            if (childPs != null) {
18678                PackageRemovedInfo childOutInfo = (outInfo != null
18679                        && outInfo.removedChildPackages != null)
18680                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18681                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18682                        && (replacingPackage != null
18683                        && !replacingPackage.hasChildPackage(childPs.name))
18684                        ? flags & ~DELETE_KEEP_DATA : flags;
18685                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18686                        deleteFlags, writeSettings);
18687            }
18688        }
18689
18690        // Delete application code and resources only for parent packages
18691        if (ps.parentPackageName == null) {
18692            if (deleteCodeAndResources && (outInfo != null)) {
18693                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18694                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18695                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18696            }
18697        }
18698
18699        return true;
18700    }
18701
18702    @Override
18703    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18704            int userId) {
18705        mContext.enforceCallingOrSelfPermission(
18706                android.Manifest.permission.DELETE_PACKAGES, null);
18707        synchronized (mPackages) {
18708            // Cannot block uninstall of static shared libs as they are
18709            // considered a part of the using app (emulating static linking).
18710            // Also static libs are installed always on internal storage.
18711            PackageParser.Package pkg = mPackages.get(packageName);
18712            if (pkg != null && pkg.staticSharedLibName != null) {
18713                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18714                        + " providing static shared library: " + pkg.staticSharedLibName);
18715                return false;
18716            }
18717            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18718            mSettings.writePackageRestrictionsLPr(userId);
18719        }
18720        return true;
18721    }
18722
18723    @Override
18724    public boolean getBlockUninstallForUser(String packageName, int userId) {
18725        synchronized (mPackages) {
18726            final PackageSetting ps = mSettings.mPackages.get(packageName);
18727            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18728                return false;
18729            }
18730            return mSettings.getBlockUninstallLPr(userId, packageName);
18731        }
18732    }
18733
18734    @Override
18735    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18736        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18737        synchronized (mPackages) {
18738            PackageSetting ps = mSettings.mPackages.get(packageName);
18739            if (ps == null) {
18740                Log.w(TAG, "Package doesn't exist: " + packageName);
18741                return false;
18742            }
18743            if (systemUserApp) {
18744                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18745            } else {
18746                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18747            }
18748            mSettings.writeLPr();
18749        }
18750        return true;
18751    }
18752
18753    /*
18754     * This method handles package deletion in general
18755     */
18756    private boolean deletePackageLIF(String packageName, UserHandle user,
18757            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18758            PackageRemovedInfo outInfo, boolean writeSettings,
18759            PackageParser.Package replacingPackage) {
18760        if (packageName == null) {
18761            Slog.w(TAG, "Attempt to delete null packageName.");
18762            return false;
18763        }
18764
18765        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18766
18767        PackageSetting ps;
18768        synchronized (mPackages) {
18769            ps = mSettings.mPackages.get(packageName);
18770            if (ps == null) {
18771                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18772                return false;
18773            }
18774
18775            if (ps.parentPackageName != null && (!isSystemApp(ps)
18776                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18777                if (DEBUG_REMOVE) {
18778                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18779                            + ((user == null) ? UserHandle.USER_ALL : user));
18780                }
18781                final int removedUserId = (user != null) ? user.getIdentifier()
18782                        : UserHandle.USER_ALL;
18783
18784                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18785                    return false;
18786                }
18787                markPackageUninstalledForUserLPw(ps, user);
18788                scheduleWritePackageRestrictionsLocked(user);
18789                return true;
18790            }
18791        }
18792
18793        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18794        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18795            onSuspendingPackageRemoved(packageName, userId);
18796        }
18797
18798
18799        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18800                && user.getIdentifier() != UserHandle.USER_ALL)) {
18801            // The caller is asking that the package only be deleted for a single
18802            // user.  To do this, we just mark its uninstalled state and delete
18803            // its data. If this is a system app, we only allow this to happen if
18804            // they have set the special DELETE_SYSTEM_APP which requests different
18805            // semantics than normal for uninstalling system apps.
18806            markPackageUninstalledForUserLPw(ps, user);
18807
18808            if (!isSystemApp(ps)) {
18809                // Do not uninstall the APK if an app should be cached
18810                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18811                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18812                    // Other user 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, "Still installed by other users");
18816                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18817                        return false;
18818                    }
18819                    scheduleWritePackageRestrictionsLocked(user);
18820                    return true;
18821                } else {
18822                    // We need to set it back to 'installed' so the uninstall
18823                    // broadcasts will be sent correctly.
18824                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18825                    ps.setInstalled(true, user.getIdentifier());
18826                    mSettings.writeKernelMappingLPr(ps);
18827                }
18828            } else {
18829                // This is a system app, so we assume that the
18830                // other users still have this package installed, so all
18831                // we need to do is clear this user's data and save that
18832                // it is uninstalled.
18833                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18834                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18835                    return false;
18836                }
18837                scheduleWritePackageRestrictionsLocked(user);
18838                return true;
18839            }
18840        }
18841
18842        // If we are deleting a composite package for all users, keep track
18843        // of result for each child.
18844        if (ps.childPackageNames != null && outInfo != null) {
18845            synchronized (mPackages) {
18846                final int childCount = ps.childPackageNames.size();
18847                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18848                for (int i = 0; i < childCount; i++) {
18849                    String childPackageName = ps.childPackageNames.get(i);
18850                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18851                    childInfo.removedPackage = childPackageName;
18852                    childInfo.installerPackageName = ps.installerPackageName;
18853                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18854                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18855                    if (childPs != null) {
18856                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18857                    }
18858                }
18859            }
18860        }
18861
18862        boolean ret = false;
18863        if (isSystemApp(ps)) {
18864            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18865            // When an updated system application is deleted we delete the existing resources
18866            // as well and fall back to existing code in system partition
18867            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18868        } else {
18869            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18870            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18871                    outInfo, writeSettings, replacingPackage);
18872        }
18873
18874        // Take a note whether we deleted the package for all users
18875        if (outInfo != null) {
18876            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18877            if (outInfo.removedChildPackages != null) {
18878                synchronized (mPackages) {
18879                    final int childCount = outInfo.removedChildPackages.size();
18880                    for (int i = 0; i < childCount; i++) {
18881                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18882                        if (childInfo != null) {
18883                            childInfo.removedForAllUsers = mPackages.get(
18884                                    childInfo.removedPackage) == null;
18885                        }
18886                    }
18887                }
18888            }
18889            // If we uninstalled an update to a system app there may be some
18890            // child packages that appeared as they are declared in the system
18891            // app but were not declared in the update.
18892            if (isSystemApp(ps)) {
18893                synchronized (mPackages) {
18894                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18895                    final int childCount = (updatedPs.childPackageNames != null)
18896                            ? updatedPs.childPackageNames.size() : 0;
18897                    for (int i = 0; i < childCount; i++) {
18898                        String childPackageName = updatedPs.childPackageNames.get(i);
18899                        if (outInfo.removedChildPackages == null
18900                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18901                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18902                            if (childPs == null) {
18903                                continue;
18904                            }
18905                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18906                            installRes.name = childPackageName;
18907                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18908                            installRes.pkg = mPackages.get(childPackageName);
18909                            installRes.uid = childPs.pkg.applicationInfo.uid;
18910                            if (outInfo.appearedChildPackages == null) {
18911                                outInfo.appearedChildPackages = new ArrayMap<>();
18912                            }
18913                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18914                        }
18915                    }
18916                }
18917            }
18918        }
18919
18920        return ret;
18921    }
18922
18923    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18924        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18925                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18926        for (int nextUserId : userIds) {
18927            if (DEBUG_REMOVE) {
18928                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18929            }
18930            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18931                    false /*installed*/,
18932                    true /*stopped*/,
18933                    true /*notLaunched*/,
18934                    false /*hidden*/,
18935                    false /*suspended*/,
18936                    null, /*suspendingPackage*/
18937                    null, /*dialogMessage*/
18938                    null, /*suspendedAppExtras*/
18939                    null, /*suspendedLauncherExtras*/
18940                    false /*instantApp*/,
18941                    false /*virtualPreload*/,
18942                    null /*lastDisableAppCaller*/,
18943                    null /*enabledComponents*/,
18944                    null /*disabledComponents*/,
18945                    ps.readUserState(nextUserId).domainVerificationStatus,
18946                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18947                    null /*harmfulAppWarning*/);
18948        }
18949        mSettings.writeKernelMappingLPr(ps);
18950    }
18951
18952    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18953            PackageRemovedInfo outInfo) {
18954        final PackageParser.Package pkg;
18955        synchronized (mPackages) {
18956            pkg = mPackages.get(ps.name);
18957        }
18958
18959        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18960                : new int[] {userId};
18961        for (int nextUserId : userIds) {
18962            if (DEBUG_REMOVE) {
18963                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18964                        + nextUserId);
18965            }
18966
18967            destroyAppDataLIF(pkg, userId,
18968                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18969            destroyAppProfilesLIF(pkg, userId);
18970            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18971            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18972            schedulePackageCleaning(ps.name, nextUserId, false);
18973            synchronized (mPackages) {
18974                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18975                    scheduleWritePackageRestrictionsLocked(nextUserId);
18976                }
18977                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18978            }
18979        }
18980
18981        if (outInfo != null) {
18982            outInfo.removedPackage = ps.name;
18983            outInfo.installerPackageName = ps.installerPackageName;
18984            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18985            outInfo.removedAppId = ps.appId;
18986            outInfo.removedUsers = userIds;
18987            outInfo.broadcastUsers = userIds;
18988        }
18989
18990        return true;
18991    }
18992
18993    private final class ClearStorageConnection implements ServiceConnection {
18994        IMediaContainerService mContainerService;
18995
18996        @Override
18997        public void onServiceConnected(ComponentName name, IBinder service) {
18998            synchronized (this) {
18999                mContainerService = IMediaContainerService.Stub
19000                        .asInterface(Binder.allowBlocking(service));
19001                notifyAll();
19002            }
19003        }
19004
19005        @Override
19006        public void onServiceDisconnected(ComponentName name) {
19007        }
19008    }
19009
19010    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19011        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19012
19013        final boolean mounted;
19014        if (Environment.isExternalStorageEmulated()) {
19015            mounted = true;
19016        } else {
19017            final String status = Environment.getExternalStorageState();
19018
19019            mounted = status.equals(Environment.MEDIA_MOUNTED)
19020                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19021        }
19022
19023        if (!mounted) {
19024            return;
19025        }
19026
19027        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19028        int[] users;
19029        if (userId == UserHandle.USER_ALL) {
19030            users = sUserManager.getUserIds();
19031        } else {
19032            users = new int[] { userId };
19033        }
19034        final ClearStorageConnection conn = new ClearStorageConnection();
19035        if (mContext.bindServiceAsUser(
19036                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19037            try {
19038                for (int curUser : users) {
19039                    long timeout = SystemClock.uptimeMillis() + 5000;
19040                    synchronized (conn) {
19041                        long now;
19042                        while (conn.mContainerService == null &&
19043                                (now = SystemClock.uptimeMillis()) < timeout) {
19044                            try {
19045                                conn.wait(timeout - now);
19046                            } catch (InterruptedException e) {
19047                            }
19048                        }
19049                    }
19050                    if (conn.mContainerService == null) {
19051                        return;
19052                    }
19053
19054                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19055                    clearDirectory(conn.mContainerService,
19056                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19057                    if (allData) {
19058                        clearDirectory(conn.mContainerService,
19059                                userEnv.buildExternalStorageAppDataDirs(packageName));
19060                        clearDirectory(conn.mContainerService,
19061                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19062                    }
19063                }
19064            } finally {
19065                mContext.unbindService(conn);
19066            }
19067        }
19068    }
19069
19070    @Override
19071    public void clearApplicationProfileData(String packageName) {
19072        enforceSystemOrRoot("Only the system can clear all profile data");
19073
19074        final PackageParser.Package pkg;
19075        synchronized (mPackages) {
19076            pkg = mPackages.get(packageName);
19077        }
19078
19079        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19080            synchronized (mInstallLock) {
19081                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19082            }
19083        }
19084    }
19085
19086    @Override
19087    public void clearApplicationUserData(final String packageName,
19088            final IPackageDataObserver observer, final int userId) {
19089        mContext.enforceCallingOrSelfPermission(
19090                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19091
19092        final int callingUid = Binder.getCallingUid();
19093        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19094                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19095
19096        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19097        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19098        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19099            throw new SecurityException("Cannot clear data for a protected package: "
19100                    + packageName);
19101        }
19102        // Queue up an async operation since the package deletion may take a little while.
19103        mHandler.post(new Runnable() {
19104            public void run() {
19105                mHandler.removeCallbacks(this);
19106                final boolean succeeded;
19107                if (!filterApp) {
19108                    try (PackageFreezer freezer = freezePackage(packageName,
19109                            "clearApplicationUserData")) {
19110                        synchronized (mInstallLock) {
19111                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19112                        }
19113                        clearExternalStorageDataSync(packageName, userId, true);
19114                        synchronized (mPackages) {
19115                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19116                                    packageName, userId);
19117                        }
19118                    }
19119                    if (succeeded) {
19120                        // invoke DeviceStorageMonitor's update method to clear any notifications
19121                        DeviceStorageMonitorInternal dsm = LocalServices
19122                                .getService(DeviceStorageMonitorInternal.class);
19123                        if (dsm != null) {
19124                            dsm.checkMemory();
19125                        }
19126                    }
19127                } else {
19128                    succeeded = false;
19129                }
19130                if (observer != null) {
19131                    try {
19132                        observer.onRemoveCompleted(packageName, succeeded);
19133                    } catch (RemoteException e) {
19134                        Log.i(TAG, "Observer no longer exists.");
19135                    }
19136                } //end if observer
19137            } //end run
19138        });
19139    }
19140
19141    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19142        if (packageName == null) {
19143            Slog.w(TAG, "Attempt to delete null packageName.");
19144            return false;
19145        }
19146
19147        // Try finding details about the requested package
19148        PackageParser.Package pkg;
19149        synchronized (mPackages) {
19150            pkg = mPackages.get(packageName);
19151            if (pkg == null) {
19152                final PackageSetting ps = mSettings.mPackages.get(packageName);
19153                if (ps != null) {
19154                    pkg = ps.pkg;
19155                }
19156            }
19157
19158            if (pkg == null) {
19159                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19160                return false;
19161            }
19162
19163            PackageSetting ps = (PackageSetting) pkg.mExtras;
19164            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19165        }
19166
19167        clearAppDataLIF(pkg, userId,
19168                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19169
19170        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19171        removeKeystoreDataIfNeeded(userId, appId);
19172
19173        UserManagerInternal umInternal = getUserManagerInternal();
19174        final int flags;
19175        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19176            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19177        } else if (umInternal.isUserRunning(userId)) {
19178            flags = StorageManager.FLAG_STORAGE_DE;
19179        } else {
19180            flags = 0;
19181        }
19182        prepareAppDataContentsLIF(pkg, userId, flags);
19183
19184        return true;
19185    }
19186
19187    /**
19188     * Reverts user permission state changes (permissions and flags) in
19189     * all packages for a given user.
19190     *
19191     * @param userId The device user for which to do a reset.
19192     */
19193    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19194        final int packageCount = mPackages.size();
19195        for (int i = 0; i < packageCount; i++) {
19196            PackageParser.Package pkg = mPackages.valueAt(i);
19197            PackageSetting ps = (PackageSetting) pkg.mExtras;
19198            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19199        }
19200    }
19201
19202    private void resetNetworkPolicies(int userId) {
19203        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19204    }
19205
19206    /**
19207     * Reverts user permission state changes (permissions and flags).
19208     *
19209     * @param ps The package for which to reset.
19210     * @param userId The device user for which to do a reset.
19211     */
19212    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19213            final PackageSetting ps, final int userId) {
19214        if (ps.pkg == null) {
19215            return;
19216        }
19217
19218        // These are flags that can change base on user actions.
19219        final int userSettableMask = FLAG_PERMISSION_USER_SET
19220                | FLAG_PERMISSION_USER_FIXED
19221                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19222                | FLAG_PERMISSION_REVIEW_REQUIRED;
19223
19224        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19225                | FLAG_PERMISSION_POLICY_FIXED;
19226
19227        boolean writeInstallPermissions = false;
19228        boolean writeRuntimePermissions = false;
19229
19230        final int permissionCount = ps.pkg.requestedPermissions.size();
19231        for (int i = 0; i < permissionCount; i++) {
19232            final String permName = ps.pkg.requestedPermissions.get(i);
19233            final BasePermission bp =
19234                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19235            if (bp == null) {
19236                continue;
19237            }
19238
19239            // If shared user we just reset the state to which only this app contributed.
19240            if (ps.sharedUser != null) {
19241                boolean used = false;
19242                final int packageCount = ps.sharedUser.packages.size();
19243                for (int j = 0; j < packageCount; j++) {
19244                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19245                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19246                            && pkg.pkg.requestedPermissions.contains(permName)) {
19247                        used = true;
19248                        break;
19249                    }
19250                }
19251                if (used) {
19252                    continue;
19253                }
19254            }
19255
19256            final PermissionsState permissionsState = ps.getPermissionsState();
19257
19258            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19259
19260            // Always clear the user settable flags.
19261            final boolean hasInstallState =
19262                    permissionsState.getInstallPermissionState(permName) != null;
19263            // If permission review is enabled and this is a legacy app, mark the
19264            // permission as requiring a review as this is the initial state.
19265            int flags = 0;
19266            if (mSettings.mPermissions.mPermissionReviewRequired
19267                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19268                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19269            }
19270            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19271                if (hasInstallState) {
19272                    writeInstallPermissions = true;
19273                } else {
19274                    writeRuntimePermissions = true;
19275                }
19276            }
19277
19278            // Below is only runtime permission handling.
19279            if (!bp.isRuntime()) {
19280                continue;
19281            }
19282
19283            // Never clobber system or policy.
19284            if ((oldFlags & policyOrSystemFlags) != 0) {
19285                continue;
19286            }
19287
19288            // If this permission was granted by default, make sure it is.
19289            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19290                if (permissionsState.grantRuntimePermission(bp, userId)
19291                        != PERMISSION_OPERATION_FAILURE) {
19292                    writeRuntimePermissions = true;
19293                }
19294            // If permission review is enabled the permissions for a legacy apps
19295            // are represented as constantly granted runtime ones, so don't revoke.
19296            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19297                // Otherwise, reset the permission.
19298                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19299                switch (revokeResult) {
19300                    case PERMISSION_OPERATION_SUCCESS:
19301                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19302                        writeRuntimePermissions = true;
19303                        final int appId = ps.appId;
19304                        mHandler.post(new Runnable() {
19305                            @Override
19306                            public void run() {
19307                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19308                            }
19309                        });
19310                    } break;
19311                }
19312            }
19313        }
19314
19315        // Synchronously write as we are taking permissions away.
19316        if (writeRuntimePermissions) {
19317            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19318        }
19319
19320        // Synchronously write as we are taking permissions away.
19321        if (writeInstallPermissions) {
19322            mSettings.writeLPr();
19323        }
19324    }
19325
19326    /**
19327     * Remove entries from the keystore daemon. Will only remove it if the
19328     * {@code appId} is valid.
19329     */
19330    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19331        if (appId < 0) {
19332            return;
19333        }
19334
19335        final KeyStore keyStore = KeyStore.getInstance();
19336        if (keyStore != null) {
19337            if (userId == UserHandle.USER_ALL) {
19338                for (final int individual : sUserManager.getUserIds()) {
19339                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19340                }
19341            } else {
19342                keyStore.clearUid(UserHandle.getUid(userId, appId));
19343            }
19344        } else {
19345            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19346        }
19347    }
19348
19349    @Override
19350    public void deleteApplicationCacheFiles(final String packageName,
19351            final IPackageDataObserver observer) {
19352        final int userId = UserHandle.getCallingUserId();
19353        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19354    }
19355
19356    @Override
19357    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19358            final IPackageDataObserver observer) {
19359        final int callingUid = Binder.getCallingUid();
19360        if (mContext.checkCallingOrSelfPermission(
19361                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19362                != PackageManager.PERMISSION_GRANTED) {
19363            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19364            if (mContext.checkCallingOrSelfPermission(
19365                    android.Manifest.permission.DELETE_CACHE_FILES)
19366                    == PackageManager.PERMISSION_GRANTED) {
19367                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19368                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19369                        ", silently ignoring");
19370                return;
19371            }
19372            mContext.enforceCallingOrSelfPermission(
19373                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19374        }
19375        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19376                /* requireFullPermission= */ true, /* checkShell= */ false,
19377                "delete application cache files");
19378        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19379                android.Manifest.permission.ACCESS_INSTANT_APPS);
19380
19381        final PackageParser.Package pkg;
19382        synchronized (mPackages) {
19383            pkg = mPackages.get(packageName);
19384        }
19385
19386        // Queue up an async operation since the package deletion may take a little while.
19387        mHandler.post(new Runnable() {
19388            public void run() {
19389                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19390                boolean doClearData = true;
19391                if (ps != null) {
19392                    final boolean targetIsInstantApp =
19393                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19394                    doClearData = !targetIsInstantApp
19395                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19396                }
19397                if (doClearData) {
19398                    synchronized (mInstallLock) {
19399                        final int flags = StorageManager.FLAG_STORAGE_DE
19400                                | StorageManager.FLAG_STORAGE_CE;
19401                        // We're only clearing cache files, so we don't care if the
19402                        // app is unfrozen and still able to run
19403                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19404                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19405                    }
19406                    clearExternalStorageDataSync(packageName, userId, false);
19407                }
19408                if (observer != null) {
19409                    try {
19410                        observer.onRemoveCompleted(packageName, true);
19411                    } catch (RemoteException e) {
19412                        Log.i(TAG, "Observer no longer exists.");
19413                    }
19414                }
19415            }
19416        });
19417    }
19418
19419    @Override
19420    public void getPackageSizeInfo(final String packageName, int userHandle,
19421            final IPackageStatsObserver observer) {
19422        throw new UnsupportedOperationException(
19423                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19424    }
19425
19426    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19427        final PackageSetting ps;
19428        synchronized (mPackages) {
19429            ps = mSettings.mPackages.get(packageName);
19430            if (ps == null) {
19431                Slog.w(TAG, "Failed to find settings for " + packageName);
19432                return false;
19433            }
19434        }
19435
19436        final String[] packageNames = { packageName };
19437        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19438        final String[] codePaths = { ps.codePathString };
19439
19440        try {
19441            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19442                    ps.appId, ceDataInodes, codePaths, stats);
19443
19444            // For now, ignore code size of packages on system partition
19445            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19446                stats.codeSize = 0;
19447            }
19448
19449            // External clients expect these to be tracked separately
19450            stats.dataSize -= stats.cacheSize;
19451
19452        } catch (InstallerException e) {
19453            Slog.w(TAG, String.valueOf(e));
19454            return false;
19455        }
19456
19457        return true;
19458    }
19459
19460    private int getUidTargetSdkVersionLockedLPr(int uid) {
19461        Object obj = mSettings.getUserIdLPr(uid);
19462        if (obj instanceof SharedUserSetting) {
19463            final SharedUserSetting sus = (SharedUserSetting) obj;
19464            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19465            final Iterator<PackageSetting> it = sus.packages.iterator();
19466            while (it.hasNext()) {
19467                final PackageSetting ps = it.next();
19468                if (ps.pkg != null) {
19469                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19470                    if (v < vers) vers = v;
19471                }
19472            }
19473            return vers;
19474        } else if (obj instanceof PackageSetting) {
19475            final PackageSetting ps = (PackageSetting) obj;
19476            if (ps.pkg != null) {
19477                return ps.pkg.applicationInfo.targetSdkVersion;
19478            }
19479        }
19480        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19481    }
19482
19483    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19484        final PackageParser.Package p = mPackages.get(packageName);
19485        if (p != null) {
19486            return p.applicationInfo.targetSdkVersion;
19487        }
19488        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19489    }
19490
19491    @Override
19492    public void addPreferredActivity(IntentFilter filter, int match,
19493            ComponentName[] set, ComponentName activity, int userId) {
19494        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19495                "Adding preferred");
19496    }
19497
19498    private void addPreferredActivityInternal(IntentFilter filter, int match,
19499            ComponentName[] set, ComponentName activity, boolean always, int userId,
19500            String opname) {
19501        // writer
19502        int callingUid = Binder.getCallingUid();
19503        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19504                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19505        if (filter.countActions() == 0) {
19506            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19507            return;
19508        }
19509        synchronized (mPackages) {
19510            if (mContext.checkCallingOrSelfPermission(
19511                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19512                    != PackageManager.PERMISSION_GRANTED) {
19513                if (getUidTargetSdkVersionLockedLPr(callingUid)
19514                        < Build.VERSION_CODES.FROYO) {
19515                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19516                            + callingUid);
19517                    return;
19518                }
19519                mContext.enforceCallingOrSelfPermission(
19520                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19521            }
19522
19523            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19524            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19525                    + userId + ":");
19526            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19527            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19528            scheduleWritePackageRestrictionsLocked(userId);
19529            postPreferredActivityChangedBroadcast(userId);
19530        }
19531    }
19532
19533    private void postPreferredActivityChangedBroadcast(int userId) {
19534        mHandler.post(() -> {
19535            final IActivityManager am = ActivityManager.getService();
19536            if (am == null) {
19537                return;
19538            }
19539
19540            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19541            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19542            try {
19543                am.broadcastIntent(null, intent, null, null,
19544                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19545                        null, false, false, userId);
19546            } catch (RemoteException e) {
19547            }
19548        });
19549    }
19550
19551    @Override
19552    public void replacePreferredActivity(IntentFilter filter, int match,
19553            ComponentName[] set, ComponentName activity, int userId) {
19554        if (filter.countActions() != 1) {
19555            throw new IllegalArgumentException(
19556                    "replacePreferredActivity expects filter to have only 1 action.");
19557        }
19558        if (filter.countDataAuthorities() != 0
19559                || filter.countDataPaths() != 0
19560                || filter.countDataSchemes() > 1
19561                || filter.countDataTypes() != 0) {
19562            throw new IllegalArgumentException(
19563                    "replacePreferredActivity expects filter to have no data authorities, " +
19564                    "paths, or types; and at most one scheme.");
19565        }
19566
19567        final int callingUid = Binder.getCallingUid();
19568        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19569                true /* requireFullPermission */, false /* checkShell */,
19570                "replace preferred activity");
19571        synchronized (mPackages) {
19572            if (mContext.checkCallingOrSelfPermission(
19573                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19574                    != PackageManager.PERMISSION_GRANTED) {
19575                if (getUidTargetSdkVersionLockedLPr(callingUid)
19576                        < Build.VERSION_CODES.FROYO) {
19577                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19578                            + Binder.getCallingUid());
19579                    return;
19580                }
19581                mContext.enforceCallingOrSelfPermission(
19582                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19583            }
19584
19585            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19586            if (pir != null) {
19587                // Get all of the existing entries that exactly match this filter.
19588                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19589                if (existing != null && existing.size() == 1) {
19590                    PreferredActivity cur = existing.get(0);
19591                    if (DEBUG_PREFERRED) {
19592                        Slog.i(TAG, "Checking replace of preferred:");
19593                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19594                        if (!cur.mPref.mAlways) {
19595                            Slog.i(TAG, "  -- CUR; not mAlways!");
19596                        } else {
19597                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19598                            Slog.i(TAG, "  -- CUR: mSet="
19599                                    + Arrays.toString(cur.mPref.mSetComponents));
19600                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19601                            Slog.i(TAG, "  -- NEW: mMatch="
19602                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19603                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19604                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19605                        }
19606                    }
19607                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19608                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19609                            && cur.mPref.sameSet(set)) {
19610                        // Setting the preferred activity to what it happens to be already
19611                        if (DEBUG_PREFERRED) {
19612                            Slog.i(TAG, "Replacing with same preferred activity "
19613                                    + cur.mPref.mShortComponent + " for user "
19614                                    + userId + ":");
19615                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19616                        }
19617                        return;
19618                    }
19619                }
19620
19621                if (existing != null) {
19622                    if (DEBUG_PREFERRED) {
19623                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19624                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19625                    }
19626                    for (int i = 0; i < existing.size(); i++) {
19627                        PreferredActivity pa = existing.get(i);
19628                        if (DEBUG_PREFERRED) {
19629                            Slog.i(TAG, "Removing existing preferred activity "
19630                                    + pa.mPref.mComponent + ":");
19631                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19632                        }
19633                        pir.removeFilter(pa);
19634                    }
19635                }
19636            }
19637            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19638                    "Replacing preferred");
19639        }
19640    }
19641
19642    @Override
19643    public void clearPackagePreferredActivities(String packageName) {
19644        final int callingUid = Binder.getCallingUid();
19645        if (getInstantAppPackageName(callingUid) != null) {
19646            return;
19647        }
19648        // writer
19649        synchronized (mPackages) {
19650            PackageParser.Package pkg = mPackages.get(packageName);
19651            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19652                if (mContext.checkCallingOrSelfPermission(
19653                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19654                        != PackageManager.PERMISSION_GRANTED) {
19655                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19656                            < Build.VERSION_CODES.FROYO) {
19657                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19658                                + callingUid);
19659                        return;
19660                    }
19661                    mContext.enforceCallingOrSelfPermission(
19662                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19663                }
19664            }
19665            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19666            if (ps != null
19667                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19668                return;
19669            }
19670            int user = UserHandle.getCallingUserId();
19671            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19672                scheduleWritePackageRestrictionsLocked(user);
19673            }
19674        }
19675    }
19676
19677    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19678    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19679        ArrayList<PreferredActivity> removed = null;
19680        boolean changed = false;
19681        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19682            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19683            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19684            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19685                continue;
19686            }
19687            Iterator<PreferredActivity> it = pir.filterIterator();
19688            while (it.hasNext()) {
19689                PreferredActivity pa = it.next();
19690                // Mark entry for removal only if it matches the package name
19691                // and the entry is of type "always".
19692                if (packageName == null ||
19693                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19694                                && pa.mPref.mAlways)) {
19695                    if (removed == null) {
19696                        removed = new ArrayList<PreferredActivity>();
19697                    }
19698                    removed.add(pa);
19699                }
19700            }
19701            if (removed != null) {
19702                for (int j=0; j<removed.size(); j++) {
19703                    PreferredActivity pa = removed.get(j);
19704                    pir.removeFilter(pa);
19705                }
19706                changed = true;
19707            }
19708        }
19709        if (changed) {
19710            postPreferredActivityChangedBroadcast(userId);
19711        }
19712        return changed;
19713    }
19714
19715    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19716    private void clearIntentFilterVerificationsLPw(int userId) {
19717        final int packageCount = mPackages.size();
19718        for (int i = 0; i < packageCount; i++) {
19719            PackageParser.Package pkg = mPackages.valueAt(i);
19720            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19721        }
19722    }
19723
19724    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19725    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19726        if (userId == UserHandle.USER_ALL) {
19727            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19728                    sUserManager.getUserIds())) {
19729                for (int oneUserId : sUserManager.getUserIds()) {
19730                    scheduleWritePackageRestrictionsLocked(oneUserId);
19731                }
19732            }
19733        } else {
19734            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19735                scheduleWritePackageRestrictionsLocked(userId);
19736            }
19737        }
19738    }
19739
19740    /** Clears state for all users, and touches intent filter verification policy */
19741    void clearDefaultBrowserIfNeeded(String packageName) {
19742        for (int oneUserId : sUserManager.getUserIds()) {
19743            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19744        }
19745    }
19746
19747    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19748        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19749        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19750            if (packageName.equals(defaultBrowserPackageName)) {
19751                setDefaultBrowserPackageName(null, userId);
19752            }
19753        }
19754    }
19755
19756    @Override
19757    public void resetApplicationPreferences(int userId) {
19758        mContext.enforceCallingOrSelfPermission(
19759                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19760        final long identity = Binder.clearCallingIdentity();
19761        // writer
19762        try {
19763            synchronized (mPackages) {
19764                clearPackagePreferredActivitiesLPw(null, userId);
19765                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19766                // TODO: We have to reset the default SMS and Phone. This requires
19767                // significant refactoring to keep all default apps in the package
19768                // manager (cleaner but more work) or have the services provide
19769                // callbacks to the package manager to request a default app reset.
19770                applyFactoryDefaultBrowserLPw(userId);
19771                clearIntentFilterVerificationsLPw(userId);
19772                primeDomainVerificationsLPw(userId);
19773                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19774                scheduleWritePackageRestrictionsLocked(userId);
19775            }
19776            resetNetworkPolicies(userId);
19777        } finally {
19778            Binder.restoreCallingIdentity(identity);
19779        }
19780    }
19781
19782    @Override
19783    public int getPreferredActivities(List<IntentFilter> outFilters,
19784            List<ComponentName> outActivities, String packageName) {
19785        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19786            return 0;
19787        }
19788        int num = 0;
19789        final int userId = UserHandle.getCallingUserId();
19790        // reader
19791        synchronized (mPackages) {
19792            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19793            if (pir != null) {
19794                final Iterator<PreferredActivity> it = pir.filterIterator();
19795                while (it.hasNext()) {
19796                    final PreferredActivity pa = it.next();
19797                    if (packageName == null
19798                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19799                                    && pa.mPref.mAlways)) {
19800                        if (outFilters != null) {
19801                            outFilters.add(new IntentFilter(pa));
19802                        }
19803                        if (outActivities != null) {
19804                            outActivities.add(pa.mPref.mComponent);
19805                        }
19806                    }
19807                }
19808            }
19809        }
19810
19811        return num;
19812    }
19813
19814    @Override
19815    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19816            int userId) {
19817        int callingUid = Binder.getCallingUid();
19818        if (callingUid != Process.SYSTEM_UID) {
19819            throw new SecurityException(
19820                    "addPersistentPreferredActivity can only be run by the system");
19821        }
19822        if (filter.countActions() == 0) {
19823            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19824            return;
19825        }
19826        synchronized (mPackages) {
19827            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19828                    ":");
19829            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19830            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19831                    new PersistentPreferredActivity(filter, activity));
19832            scheduleWritePackageRestrictionsLocked(userId);
19833            postPreferredActivityChangedBroadcast(userId);
19834        }
19835    }
19836
19837    @Override
19838    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19839        int callingUid = Binder.getCallingUid();
19840        if (callingUid != Process.SYSTEM_UID) {
19841            throw new SecurityException(
19842                    "clearPackagePersistentPreferredActivities can only be run by the system");
19843        }
19844        ArrayList<PersistentPreferredActivity> removed = null;
19845        boolean changed = false;
19846        synchronized (mPackages) {
19847            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19848                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19849                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19850                        .valueAt(i);
19851                if (userId != thisUserId) {
19852                    continue;
19853                }
19854                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19855                while (it.hasNext()) {
19856                    PersistentPreferredActivity ppa = it.next();
19857                    // Mark entry for removal only if it matches the package name.
19858                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19859                        if (removed == null) {
19860                            removed = new ArrayList<PersistentPreferredActivity>();
19861                        }
19862                        removed.add(ppa);
19863                    }
19864                }
19865                if (removed != null) {
19866                    for (int j=0; j<removed.size(); j++) {
19867                        PersistentPreferredActivity ppa = removed.get(j);
19868                        ppir.removeFilter(ppa);
19869                    }
19870                    changed = true;
19871                }
19872            }
19873
19874            if (changed) {
19875                scheduleWritePackageRestrictionsLocked(userId);
19876                postPreferredActivityChangedBroadcast(userId);
19877            }
19878        }
19879    }
19880
19881    /**
19882     * Common machinery for picking apart a restored XML blob and passing
19883     * it to a caller-supplied functor to be applied to the running system.
19884     */
19885    private void restoreFromXml(XmlPullParser parser, int userId,
19886            String expectedStartTag, BlobXmlRestorer functor)
19887            throws IOException, XmlPullParserException {
19888        int type;
19889        while ((type = parser.next()) != XmlPullParser.START_TAG
19890                && type != XmlPullParser.END_DOCUMENT) {
19891        }
19892        if (type != XmlPullParser.START_TAG) {
19893            // oops didn't find a start tag?!
19894            if (DEBUG_BACKUP) {
19895                Slog.e(TAG, "Didn't find start tag during restore");
19896            }
19897            return;
19898        }
19899Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19900        // this is supposed to be TAG_PREFERRED_BACKUP
19901        if (!expectedStartTag.equals(parser.getName())) {
19902            if (DEBUG_BACKUP) {
19903                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19904            }
19905            return;
19906        }
19907
19908        // skip interfering stuff, then we're aligned with the backing implementation
19909        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19910Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19911        functor.apply(parser, userId);
19912    }
19913
19914    private interface BlobXmlRestorer {
19915        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19916    }
19917
19918    /**
19919     * Non-Binder method, support for the backup/restore mechanism: write the
19920     * full set of preferred activities in its canonical XML format.  Returns the
19921     * XML output as a byte array, or null if there is none.
19922     */
19923    @Override
19924    public byte[] getPreferredActivityBackup(int userId) {
19925        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19926            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19927        }
19928
19929        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19930        try {
19931            final XmlSerializer serializer = new FastXmlSerializer();
19932            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19933            serializer.startDocument(null, true);
19934            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19935
19936            synchronized (mPackages) {
19937                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19938            }
19939
19940            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19941            serializer.endDocument();
19942            serializer.flush();
19943        } catch (Exception e) {
19944            if (DEBUG_BACKUP) {
19945                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19946            }
19947            return null;
19948        }
19949
19950        return dataStream.toByteArray();
19951    }
19952
19953    @Override
19954    public void restorePreferredActivities(byte[] backup, int userId) {
19955        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19956            throw new SecurityException("Only the system may call restorePreferredActivities()");
19957        }
19958
19959        try {
19960            final XmlPullParser parser = Xml.newPullParser();
19961            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19962            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19963                    new BlobXmlRestorer() {
19964                        @Override
19965                        public void apply(XmlPullParser parser, int userId)
19966                                throws XmlPullParserException, IOException {
19967                            synchronized (mPackages) {
19968                                mSettings.readPreferredActivitiesLPw(parser, userId);
19969                            }
19970                        }
19971                    } );
19972        } catch (Exception e) {
19973            if (DEBUG_BACKUP) {
19974                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19975            }
19976        }
19977    }
19978
19979    /**
19980     * Non-Binder method, support for the backup/restore mechanism: write the
19981     * default browser (etc) settings in its canonical XML format.  Returns the default
19982     * browser XML representation as a byte array, or null if there is none.
19983     */
19984    @Override
19985    public byte[] getDefaultAppsBackup(int userId) {
19986        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19987            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19988        }
19989
19990        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19991        try {
19992            final XmlSerializer serializer = new FastXmlSerializer();
19993            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19994            serializer.startDocument(null, true);
19995            serializer.startTag(null, TAG_DEFAULT_APPS);
19996
19997            synchronized (mPackages) {
19998                mSettings.writeDefaultAppsLPr(serializer, userId);
19999            }
20000
20001            serializer.endTag(null, TAG_DEFAULT_APPS);
20002            serializer.endDocument();
20003            serializer.flush();
20004        } catch (Exception e) {
20005            if (DEBUG_BACKUP) {
20006                Slog.e(TAG, "Unable to write default apps for backup", e);
20007            }
20008            return null;
20009        }
20010
20011        return dataStream.toByteArray();
20012    }
20013
20014    @Override
20015    public void restoreDefaultApps(byte[] backup, int userId) {
20016        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20017            throw new SecurityException("Only the system may call restoreDefaultApps()");
20018        }
20019
20020        try {
20021            final XmlPullParser parser = Xml.newPullParser();
20022            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20023            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20024                    new BlobXmlRestorer() {
20025                        @Override
20026                        public void apply(XmlPullParser parser, int userId)
20027                                throws XmlPullParserException, IOException {
20028                            synchronized (mPackages) {
20029                                mSettings.readDefaultAppsLPw(parser, userId);
20030                            }
20031                        }
20032                    } );
20033        } catch (Exception e) {
20034            if (DEBUG_BACKUP) {
20035                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20036            }
20037        }
20038    }
20039
20040    @Override
20041    public byte[] getIntentFilterVerificationBackup(int userId) {
20042        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20043            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20044        }
20045
20046        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20047        try {
20048            final XmlSerializer serializer = new FastXmlSerializer();
20049            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20050            serializer.startDocument(null, true);
20051            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20052
20053            synchronized (mPackages) {
20054                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20055            }
20056
20057            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20058            serializer.endDocument();
20059            serializer.flush();
20060        } catch (Exception e) {
20061            if (DEBUG_BACKUP) {
20062                Slog.e(TAG, "Unable to write default apps for backup", e);
20063            }
20064            return null;
20065        }
20066
20067        return dataStream.toByteArray();
20068    }
20069
20070    @Override
20071    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20072        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20073            throw new SecurityException("Only the system may call restorePreferredActivities()");
20074        }
20075
20076        try {
20077            final XmlPullParser parser = Xml.newPullParser();
20078            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20079            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20080                    new BlobXmlRestorer() {
20081                        @Override
20082                        public void apply(XmlPullParser parser, int userId)
20083                                throws XmlPullParserException, IOException {
20084                            synchronized (mPackages) {
20085                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20086                                mSettings.writeLPr();
20087                            }
20088                        }
20089                    } );
20090        } catch (Exception e) {
20091            if (DEBUG_BACKUP) {
20092                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20093            }
20094        }
20095    }
20096
20097    @Override
20098    public byte[] getPermissionGrantBackup(int userId) {
20099        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20100            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20101        }
20102
20103        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20104        try {
20105            final XmlSerializer serializer = new FastXmlSerializer();
20106            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20107            serializer.startDocument(null, true);
20108            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20109
20110            synchronized (mPackages) {
20111                serializeRuntimePermissionGrantsLPr(serializer, userId);
20112            }
20113
20114            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20115            serializer.endDocument();
20116            serializer.flush();
20117        } catch (Exception e) {
20118            if (DEBUG_BACKUP) {
20119                Slog.e(TAG, "Unable to write default apps for backup", e);
20120            }
20121            return null;
20122        }
20123
20124        return dataStream.toByteArray();
20125    }
20126
20127    @Override
20128    public void restorePermissionGrants(byte[] backup, int userId) {
20129        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20130            throw new SecurityException("Only the system may call restorePermissionGrants()");
20131        }
20132
20133        try {
20134            final XmlPullParser parser = Xml.newPullParser();
20135            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20136            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20137                    new BlobXmlRestorer() {
20138                        @Override
20139                        public void apply(XmlPullParser parser, int userId)
20140                                throws XmlPullParserException, IOException {
20141                            synchronized (mPackages) {
20142                                processRestoredPermissionGrantsLPr(parser, userId);
20143                            }
20144                        }
20145                    } );
20146        } catch (Exception e) {
20147            if (DEBUG_BACKUP) {
20148                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20149            }
20150        }
20151    }
20152
20153    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20154            throws IOException {
20155        serializer.startTag(null, TAG_ALL_GRANTS);
20156
20157        final int N = mSettings.mPackages.size();
20158        for (int i = 0; i < N; i++) {
20159            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20160            boolean pkgGrantsKnown = false;
20161
20162            PermissionsState packagePerms = ps.getPermissionsState();
20163
20164            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20165                final int grantFlags = state.getFlags();
20166                // only look at grants that are not system/policy fixed
20167                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20168                    final boolean isGranted = state.isGranted();
20169                    // And only back up the user-twiddled state bits
20170                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20171                        final String packageName = mSettings.mPackages.keyAt(i);
20172                        if (!pkgGrantsKnown) {
20173                            serializer.startTag(null, TAG_GRANT);
20174                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20175                            pkgGrantsKnown = true;
20176                        }
20177
20178                        final boolean userSet =
20179                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20180                        final boolean userFixed =
20181                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20182                        final boolean revoke =
20183                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20184
20185                        serializer.startTag(null, TAG_PERMISSION);
20186                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20187                        if (isGranted) {
20188                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20189                        }
20190                        if (userSet) {
20191                            serializer.attribute(null, ATTR_USER_SET, "true");
20192                        }
20193                        if (userFixed) {
20194                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20195                        }
20196                        if (revoke) {
20197                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20198                        }
20199                        serializer.endTag(null, TAG_PERMISSION);
20200                    }
20201                }
20202            }
20203
20204            if (pkgGrantsKnown) {
20205                serializer.endTag(null, TAG_GRANT);
20206            }
20207        }
20208
20209        serializer.endTag(null, TAG_ALL_GRANTS);
20210    }
20211
20212    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20213            throws XmlPullParserException, IOException {
20214        String pkgName = null;
20215        int outerDepth = parser.getDepth();
20216        int type;
20217        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20218                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20219            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20220                continue;
20221            }
20222
20223            final String tagName = parser.getName();
20224            if (tagName.equals(TAG_GRANT)) {
20225                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20226                if (DEBUG_BACKUP) {
20227                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20228                }
20229            } else if (tagName.equals(TAG_PERMISSION)) {
20230
20231                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20232                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20233
20234                int newFlagSet = 0;
20235                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20236                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20237                }
20238                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20239                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20240                }
20241                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20242                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20243                }
20244                if (DEBUG_BACKUP) {
20245                    Slog.v(TAG, "  + Restoring grant:"
20246                            + " pkg=" + pkgName
20247                            + " perm=" + permName
20248                            + " granted=" + isGranted
20249                            + " bits=0x" + Integer.toHexString(newFlagSet));
20250                }
20251                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20252                if (ps != null) {
20253                    // Already installed so we apply the grant immediately
20254                    if (DEBUG_BACKUP) {
20255                        Slog.v(TAG, "        + already installed; applying");
20256                    }
20257                    PermissionsState perms = ps.getPermissionsState();
20258                    BasePermission bp =
20259                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20260                    if (bp != null) {
20261                        if (isGranted) {
20262                            perms.grantRuntimePermission(bp, userId);
20263                        }
20264                        if (newFlagSet != 0) {
20265                            perms.updatePermissionFlags(
20266                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20267                        }
20268                    }
20269                } else {
20270                    // Need to wait for post-restore install to apply the grant
20271                    if (DEBUG_BACKUP) {
20272                        Slog.v(TAG, "        - not yet installed; saving for later");
20273                    }
20274                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20275                            isGranted, newFlagSet, userId);
20276                }
20277            } else {
20278                PackageManagerService.reportSettingsProblem(Log.WARN,
20279                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20280                XmlUtils.skipCurrentTag(parser);
20281            }
20282        }
20283
20284        scheduleWriteSettingsLocked();
20285        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20286    }
20287
20288    @Override
20289    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20290            int sourceUserId, int targetUserId, int flags) {
20291        mContext.enforceCallingOrSelfPermission(
20292                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20293        int callingUid = Binder.getCallingUid();
20294        enforceOwnerRights(ownerPackage, callingUid);
20295        PackageManagerServiceUtils.enforceShellRestriction(
20296                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20297        if (intentFilter.countActions() == 0) {
20298            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20299            return;
20300        }
20301        synchronized (mPackages) {
20302            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20303                    ownerPackage, targetUserId, flags);
20304            CrossProfileIntentResolver resolver =
20305                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20306            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20307            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20308            if (existing != null) {
20309                int size = existing.size();
20310                for (int i = 0; i < size; i++) {
20311                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20312                        return;
20313                    }
20314                }
20315            }
20316            resolver.addFilter(newFilter);
20317            scheduleWritePackageRestrictionsLocked(sourceUserId);
20318        }
20319    }
20320
20321    @Override
20322    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20323        mContext.enforceCallingOrSelfPermission(
20324                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20325        final int callingUid = Binder.getCallingUid();
20326        enforceOwnerRights(ownerPackage, callingUid);
20327        PackageManagerServiceUtils.enforceShellRestriction(
20328                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20329        synchronized (mPackages) {
20330            CrossProfileIntentResolver resolver =
20331                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20332            ArraySet<CrossProfileIntentFilter> set =
20333                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20334            for (CrossProfileIntentFilter filter : set) {
20335                if (filter.getOwnerPackage().equals(ownerPackage)) {
20336                    resolver.removeFilter(filter);
20337                }
20338            }
20339            scheduleWritePackageRestrictionsLocked(sourceUserId);
20340        }
20341    }
20342
20343    // Enforcing that callingUid is owning pkg on userId
20344    private void enforceOwnerRights(String pkg, int callingUid) {
20345        // The system owns everything.
20346        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20347            return;
20348        }
20349        final int callingUserId = UserHandle.getUserId(callingUid);
20350        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20351        if (pi == null) {
20352            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20353                    + callingUserId);
20354        }
20355        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20356            throw new SecurityException("Calling uid " + callingUid
20357                    + " does not own package " + pkg);
20358        }
20359    }
20360
20361    @Override
20362    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20364            return null;
20365        }
20366        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20367    }
20368
20369    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20370        UserManagerService ums = UserManagerService.getInstance();
20371        if (ums != null) {
20372            final UserInfo parent = ums.getProfileParent(userId);
20373            final int launcherUid = (parent != null) ? parent.id : userId;
20374            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20375            if (launcherComponent != null) {
20376                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20377                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20378                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20379                        .setPackage(launcherComponent.getPackageName());
20380                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20381            }
20382        }
20383    }
20384
20385    /**
20386     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20387     * then reports the most likely home activity or null if there are more than one.
20388     */
20389    private ComponentName getDefaultHomeActivity(int userId) {
20390        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20391        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20392        if (cn != null) {
20393            return cn;
20394        }
20395
20396        // Find the launcher with the highest priority and return that component if there are no
20397        // other home activity with the same priority.
20398        int lastPriority = Integer.MIN_VALUE;
20399        ComponentName lastComponent = null;
20400        final int size = allHomeCandidates.size();
20401        for (int i = 0; i < size; i++) {
20402            final ResolveInfo ri = allHomeCandidates.get(i);
20403            if (ri.priority > lastPriority) {
20404                lastComponent = ri.activityInfo.getComponentName();
20405                lastPriority = ri.priority;
20406            } else if (ri.priority == lastPriority) {
20407                // Two components found with same priority.
20408                lastComponent = null;
20409            }
20410        }
20411        return lastComponent;
20412    }
20413
20414    private Intent getHomeIntent() {
20415        Intent intent = new Intent(Intent.ACTION_MAIN);
20416        intent.addCategory(Intent.CATEGORY_HOME);
20417        intent.addCategory(Intent.CATEGORY_DEFAULT);
20418        return intent;
20419    }
20420
20421    private IntentFilter getHomeFilter() {
20422        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20423        filter.addCategory(Intent.CATEGORY_HOME);
20424        filter.addCategory(Intent.CATEGORY_DEFAULT);
20425        return filter;
20426    }
20427
20428    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20429            int userId) {
20430        Intent intent  = getHomeIntent();
20431        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20432                PackageManager.GET_META_DATA, userId);
20433        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20434                true, false, false, userId);
20435
20436        allHomeCandidates.clear();
20437        if (list != null) {
20438            for (ResolveInfo ri : list) {
20439                allHomeCandidates.add(ri);
20440            }
20441        }
20442        return (preferred == null || preferred.activityInfo == null)
20443                ? null
20444                : new ComponentName(preferred.activityInfo.packageName,
20445                        preferred.activityInfo.name);
20446    }
20447
20448    @Override
20449    public void setHomeActivity(ComponentName comp, int userId) {
20450        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20451            return;
20452        }
20453        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20454        getHomeActivitiesAsUser(homeActivities, userId);
20455
20456        boolean found = false;
20457
20458        final int size = homeActivities.size();
20459        final ComponentName[] set = new ComponentName[size];
20460        for (int i = 0; i < size; i++) {
20461            final ResolveInfo candidate = homeActivities.get(i);
20462            final ActivityInfo info = candidate.activityInfo;
20463            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20464            set[i] = activityName;
20465            if (!found && activityName.equals(comp)) {
20466                found = true;
20467            }
20468        }
20469        if (!found) {
20470            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20471                    + userId);
20472        }
20473        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20474                set, comp, userId);
20475    }
20476
20477    private @Nullable String getSetupWizardPackageName() {
20478        final Intent intent = new Intent(Intent.ACTION_MAIN);
20479        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20480
20481        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20482                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20483                        | MATCH_DISABLED_COMPONENTS,
20484                UserHandle.myUserId());
20485        if (matches.size() == 1) {
20486            return matches.get(0).getComponentInfo().packageName;
20487        } else {
20488            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20489                    + ": matches=" + matches);
20490            return null;
20491        }
20492    }
20493
20494    private @Nullable String getStorageManagerPackageName() {
20495        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20496
20497        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20498                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20499                        | MATCH_DISABLED_COMPONENTS,
20500                UserHandle.myUserId());
20501        if (matches.size() == 1) {
20502            return matches.get(0).getComponentInfo().packageName;
20503        } else {
20504            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20505                    + matches.size() + ": matches=" + matches);
20506            return null;
20507        }
20508    }
20509
20510    @Override
20511    public String getSystemTextClassifierPackageName() {
20512        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20513    }
20514
20515    @Override
20516    public void setApplicationEnabledSetting(String appPackageName,
20517            int newState, int flags, int userId, String callingPackage) {
20518        if (!sUserManager.exists(userId)) return;
20519        if (callingPackage == null) {
20520            callingPackage = Integer.toString(Binder.getCallingUid());
20521        }
20522        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20523    }
20524
20525    @Override
20526    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20527        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20528        synchronized (mPackages) {
20529            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20530            if (pkgSetting != null) {
20531                pkgSetting.setUpdateAvailable(updateAvailable);
20532            }
20533        }
20534    }
20535
20536    @Override
20537    public void setComponentEnabledSetting(ComponentName componentName,
20538            int newState, int flags, int userId) {
20539        if (!sUserManager.exists(userId)) return;
20540        setEnabledSetting(componentName.getPackageName(),
20541                componentName.getClassName(), newState, flags, userId, null);
20542    }
20543
20544    private void setEnabledSetting(final String packageName, String className, int newState,
20545            final int flags, int userId, String callingPackage) {
20546        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20547              || newState == COMPONENT_ENABLED_STATE_ENABLED
20548              || newState == COMPONENT_ENABLED_STATE_DISABLED
20549              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20550              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20551            throw new IllegalArgumentException("Invalid new component state: "
20552                    + newState);
20553        }
20554        PackageSetting pkgSetting;
20555        final int callingUid = Binder.getCallingUid();
20556        final int permission;
20557        if (callingUid == Process.SYSTEM_UID) {
20558            permission = PackageManager.PERMISSION_GRANTED;
20559        } else {
20560            permission = mContext.checkCallingOrSelfPermission(
20561                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20562        }
20563        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20564                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20565        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20566        boolean sendNow = false;
20567        boolean isApp = (className == null);
20568        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20569        String componentName = isApp ? packageName : className;
20570        int packageUid = -1;
20571        ArrayList<String> components;
20572
20573        // reader
20574        synchronized (mPackages) {
20575            pkgSetting = mSettings.mPackages.get(packageName);
20576            if (pkgSetting == null) {
20577                if (!isCallerInstantApp) {
20578                    if (className == null) {
20579                        throw new IllegalArgumentException("Unknown package: " + packageName);
20580                    }
20581                    throw new IllegalArgumentException(
20582                            "Unknown component: " + packageName + "/" + className);
20583                } else {
20584                    // throw SecurityException to prevent leaking package information
20585                    throw new SecurityException(
20586                            "Attempt to change component state; "
20587                            + "pid=" + Binder.getCallingPid()
20588                            + ", uid=" + callingUid
20589                            + (className == null
20590                                    ? ", package=" + packageName
20591                                    : ", component=" + packageName + "/" + className));
20592                }
20593            }
20594        }
20595
20596        // Limit who can change which apps
20597        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20598            // Don't allow apps that don't have permission to modify other apps
20599            if (!allowedByPermission
20600                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20601                throw new SecurityException(
20602                        "Attempt to change component state; "
20603                        + "pid=" + Binder.getCallingPid()
20604                        + ", uid=" + callingUid
20605                        + (className == null
20606                                ? ", package=" + packageName
20607                                : ", component=" + packageName + "/" + className));
20608            }
20609            // Don't allow changing protected packages.
20610            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20611                throw new SecurityException("Cannot disable a protected package: " + packageName);
20612            }
20613        }
20614
20615        synchronized (mPackages) {
20616            if (callingUid == Process.SHELL_UID
20617                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20618                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20619                // unless it is a test package.
20620                int oldState = pkgSetting.getEnabled(userId);
20621                if (className == null
20622                        &&
20623                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20624                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20625                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20626                        &&
20627                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20628                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20629                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20630                    // ok
20631                } else {
20632                    throw new SecurityException(
20633                            "Shell cannot change component state for " + packageName + "/"
20634                                    + className + " to " + newState);
20635                }
20636            }
20637        }
20638        if (className == null) {
20639            // We're dealing with an application/package level state change
20640            synchronized (mPackages) {
20641                if (pkgSetting.getEnabled(userId) == newState) {
20642                    // Nothing to do
20643                    return;
20644                }
20645            }
20646            // If we're enabling a system stub, there's a little more work to do.
20647            // Prior to enabling the package, we need to decompress the APK(s) to the
20648            // data partition and then replace the version on the system partition.
20649            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20650            final boolean isSystemStub = deletedPkg.isStub
20651                    && deletedPkg.isSystem();
20652            if (isSystemStub
20653                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20654                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20655                final File codePath = decompressPackage(deletedPkg);
20656                if (codePath == null) {
20657                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20658                    return;
20659                }
20660                // TODO remove direct parsing of the package object during internal cleanup
20661                // of scan package
20662                // We need to call parse directly here for no other reason than we need
20663                // the new package in order to disable the old one [we use the information
20664                // for some internal optimization to optionally create a new package setting
20665                // object on replace]. However, we can't get the package from the scan
20666                // because the scan modifies live structures and we need to remove the
20667                // old [system] package from the system before a scan can be attempted.
20668                // Once scan is indempotent we can remove this parse and use the package
20669                // object we scanned, prior to adding it to package settings.
20670                final PackageParser pp = new PackageParser();
20671                pp.setSeparateProcesses(mSeparateProcesses);
20672                pp.setDisplayMetrics(mMetrics);
20673                pp.setCallback(mPackageParserCallback);
20674                final PackageParser.Package tmpPkg;
20675                try {
20676                    final @ParseFlags int parseFlags = mDefParseFlags
20677                            | PackageParser.PARSE_MUST_BE_APK
20678                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20679                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20680                } catch (PackageParserException e) {
20681                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20682                    return;
20683                }
20684                synchronized (mInstallLock) {
20685                    // Disable the stub and remove any package entries
20686                    removePackageLI(deletedPkg, true);
20687                    synchronized (mPackages) {
20688                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20689                    }
20690                    final PackageParser.Package pkg;
20691                    try (PackageFreezer freezer =
20692                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20693                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20694                                | PackageParser.PARSE_ENFORCE_CODE;
20695                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20696                                0 /*currentTime*/, null /*user*/);
20697                        prepareAppDataAfterInstallLIF(pkg);
20698                        synchronized (mPackages) {
20699                            try {
20700                                updateSharedLibrariesLPr(pkg, null);
20701                            } catch (PackageManagerException e) {
20702                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20703                            }
20704                            mPermissionManager.updatePermissions(
20705                                    pkg.packageName, pkg, true, mPackages.values(),
20706                                    mPermissionCallback);
20707                            mSettings.writeLPr();
20708                        }
20709                    } catch (PackageManagerException e) {
20710                        // Whoops! Something went wrong; try to roll back to the stub
20711                        Slog.w(TAG, "Failed to install compressed system package:"
20712                                + pkgSetting.name, e);
20713                        // Remove the failed install
20714                        removeCodePathLI(codePath);
20715
20716                        // Install the system package
20717                        try (PackageFreezer freezer =
20718                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20719                            synchronized (mPackages) {
20720                                // NOTE: The system package always needs to be enabled; even
20721                                // if it's for a compressed stub. If we don't, installing the
20722                                // system package fails during scan [scanning checks the disabled
20723                                // packages]. We will reverse this later, after we've "installed"
20724                                // the stub.
20725                                // This leaves us in a fragile state; the stub should never be
20726                                // enabled, so, cross your fingers and hope nothing goes wrong
20727                                // until we can disable the package later.
20728                                enableSystemPackageLPw(deletedPkg);
20729                            }
20730                            installPackageFromSystemLIF(deletedPkg.codePath,
20731                                    false /*isPrivileged*/, null /*allUserHandles*/,
20732                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20733                                    true /*writeSettings*/);
20734                        } catch (PackageManagerException pme) {
20735                            Slog.w(TAG, "Failed to restore system package:"
20736                                    + deletedPkg.packageName, pme);
20737                        } finally {
20738                            synchronized (mPackages) {
20739                                mSettings.disableSystemPackageLPw(
20740                                        deletedPkg.packageName, true /*replaced*/);
20741                                mSettings.writeLPr();
20742                            }
20743                        }
20744                        return;
20745                    }
20746                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20747                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20748                    mDexManager.notifyPackageUpdated(pkg.packageName,
20749                            pkg.baseCodePath, pkg.splitCodePaths);
20750                }
20751            }
20752            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20753                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20754                // Don't care about who enables an app.
20755                callingPackage = null;
20756            }
20757            synchronized (mPackages) {
20758                pkgSetting.setEnabled(newState, userId, callingPackage);
20759            }
20760        } else {
20761            synchronized (mPackages) {
20762                // We're dealing with a component level state change
20763                // First, verify that this is a valid class name.
20764                PackageParser.Package pkg = pkgSetting.pkg;
20765                if (pkg == null || !pkg.hasComponentClassName(className)) {
20766                    if (pkg != null &&
20767                            pkg.applicationInfo.targetSdkVersion >=
20768                                    Build.VERSION_CODES.JELLY_BEAN) {
20769                        throw new IllegalArgumentException("Component class " + className
20770                                + " does not exist in " + packageName);
20771                    } else {
20772                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20773                                + className + " does not exist in " + packageName);
20774                    }
20775                }
20776                switch (newState) {
20777                    case COMPONENT_ENABLED_STATE_ENABLED:
20778                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20779                            return;
20780                        }
20781                        break;
20782                    case COMPONENT_ENABLED_STATE_DISABLED:
20783                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20784                            return;
20785                        }
20786                        break;
20787                    case COMPONENT_ENABLED_STATE_DEFAULT:
20788                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20789                            return;
20790                        }
20791                        break;
20792                    default:
20793                        Slog.e(TAG, "Invalid new component state: " + newState);
20794                        return;
20795                }
20796            }
20797        }
20798        synchronized (mPackages) {
20799            scheduleWritePackageRestrictionsLocked(userId);
20800            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20801            final long callingId = Binder.clearCallingIdentity();
20802            try {
20803                updateInstantAppInstallerLocked(packageName);
20804            } finally {
20805                Binder.restoreCallingIdentity(callingId);
20806            }
20807            components = mPendingBroadcasts.get(userId, packageName);
20808            final boolean newPackage = components == null;
20809            if (newPackage) {
20810                components = new ArrayList<String>();
20811            }
20812            if (!components.contains(componentName)) {
20813                components.add(componentName);
20814            }
20815            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20816                sendNow = true;
20817                // Purge entry from pending broadcast list if another one exists already
20818                // since we are sending one right away.
20819                mPendingBroadcasts.remove(userId, packageName);
20820            } else {
20821                if (newPackage) {
20822                    mPendingBroadcasts.put(userId, packageName, components);
20823                }
20824                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20825                    // Schedule a message
20826                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20827                }
20828            }
20829        }
20830
20831        long callingId = Binder.clearCallingIdentity();
20832        try {
20833            if (sendNow) {
20834                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20835                sendPackageChangedBroadcast(packageName,
20836                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20837            }
20838        } finally {
20839            Binder.restoreCallingIdentity(callingId);
20840        }
20841    }
20842
20843    @Override
20844    public void flushPackageRestrictionsAsUser(int userId) {
20845        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20846            return;
20847        }
20848        if (!sUserManager.exists(userId)) {
20849            return;
20850        }
20851        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20852                false /* checkShell */, "flushPackageRestrictions");
20853        synchronized (mPackages) {
20854            mSettings.writePackageRestrictionsLPr(userId);
20855            mDirtyUsers.remove(userId);
20856            if (mDirtyUsers.isEmpty()) {
20857                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20858            }
20859        }
20860    }
20861
20862    private void sendPackageChangedBroadcast(String packageName,
20863            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20864        if (DEBUG_INSTALL)
20865            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20866                    + componentNames);
20867        Bundle extras = new Bundle(4);
20868        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20869        String nameList[] = new String[componentNames.size()];
20870        componentNames.toArray(nameList);
20871        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20872        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20873        extras.putInt(Intent.EXTRA_UID, packageUid);
20874        // If this is not reporting a change of the overall package, then only send it
20875        // to registered receivers.  We don't want to launch a swath of apps for every
20876        // little component state change.
20877        final int flags = !componentNames.contains(packageName)
20878                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20879        final int userId = UserHandle.getUserId(packageUid);
20880        final boolean isInstantApp = isInstantApp(packageName, userId);
20881        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20882        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20883        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20884                userIds, instantUserIds);
20885    }
20886
20887    @Override
20888    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20889        if (!sUserManager.exists(userId)) return;
20890        final int callingUid = Binder.getCallingUid();
20891        if (getInstantAppPackageName(callingUid) != null) {
20892            return;
20893        }
20894        final int permission = mContext.checkCallingOrSelfPermission(
20895                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20896        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20897        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20898                true /* requireFullPermission */, true /* checkShell */, "stop package");
20899        // writer
20900        synchronized (mPackages) {
20901            final PackageSetting ps = mSettings.mPackages.get(packageName);
20902            if (!filterAppAccessLPr(ps, callingUid, userId)
20903                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20904                            allowedByPermission, callingUid, userId)) {
20905                scheduleWritePackageRestrictionsLocked(userId);
20906            }
20907        }
20908    }
20909
20910    @Override
20911    public String getInstallerPackageName(String packageName) {
20912        final int callingUid = Binder.getCallingUid();
20913        synchronized (mPackages) {
20914            final PackageSetting ps = mSettings.mPackages.get(packageName);
20915            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20916                return null;
20917            }
20918            return mSettings.getInstallerPackageNameLPr(packageName);
20919        }
20920    }
20921
20922    public boolean isOrphaned(String packageName) {
20923        // reader
20924        synchronized (mPackages) {
20925            return mSettings.isOrphaned(packageName);
20926        }
20927    }
20928
20929    @Override
20930    public int getApplicationEnabledSetting(String packageName, int userId) {
20931        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20932        int callingUid = Binder.getCallingUid();
20933        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20934                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20935        // reader
20936        synchronized (mPackages) {
20937            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20938                return COMPONENT_ENABLED_STATE_DISABLED;
20939            }
20940            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20941        }
20942    }
20943
20944    @Override
20945    public int getComponentEnabledSetting(ComponentName component, int userId) {
20946        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20947        int callingUid = Binder.getCallingUid();
20948        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20949                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20950        synchronized (mPackages) {
20951            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20952                    component, TYPE_UNKNOWN, userId)) {
20953                return COMPONENT_ENABLED_STATE_DISABLED;
20954            }
20955            return mSettings.getComponentEnabledSettingLPr(component, userId);
20956        }
20957    }
20958
20959    @Override
20960    public void enterSafeMode() {
20961        enforceSystemOrRoot("Only the system can request entering safe mode");
20962
20963        if (!mSystemReady) {
20964            mSafeMode = true;
20965        }
20966    }
20967
20968    @Override
20969    public void systemReady() {
20970        enforceSystemOrRoot("Only the system can claim the system is ready");
20971
20972        mSystemReady = true;
20973        final ContentResolver resolver = mContext.getContentResolver();
20974        ContentObserver co = new ContentObserver(mHandler) {
20975            @Override
20976            public void onChange(boolean selfChange) {
20977                mWebInstantAppsDisabled =
20978                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20979                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20980            }
20981        };
20982        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20983                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20984                false, co, UserHandle.USER_SYSTEM);
20985        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20986                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20987        co.onChange(true);
20988
20989        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20990        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20991        // it is done.
20992        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20993            @Override
20994            public void onChange(boolean selfChange) {
20995                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20996                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20997                        oobEnabled == 1 ? "true" : "false");
20998            }
20999        };
21000        mContext.getContentResolver().registerContentObserver(
21001                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
21002                UserHandle.USER_SYSTEM);
21003        // At boot, restore the value from the setting, which persists across reboot.
21004        privAppOobObserver.onChange(true);
21005
21006        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21007        // disabled after already being started.
21008        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21009                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21010
21011        // Read the compatibilty setting when the system is ready.
21012        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21013                mContext.getContentResolver(),
21014                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21015        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21016        if (DEBUG_SETTINGS) {
21017            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21018        }
21019
21020        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21021
21022        synchronized (mPackages) {
21023            // Verify that all of the preferred activity components actually
21024            // exist.  It is possible for applications to be updated and at
21025            // that point remove a previously declared activity component that
21026            // had been set as a preferred activity.  We try to clean this up
21027            // the next time we encounter that preferred activity, but it is
21028            // possible for the user flow to never be able to return to that
21029            // situation so here we do a sanity check to make sure we haven't
21030            // left any junk around.
21031            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21032            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21033                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21034                removed.clear();
21035                for (PreferredActivity pa : pir.filterSet()) {
21036                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21037                        removed.add(pa);
21038                    }
21039                }
21040                if (removed.size() > 0) {
21041                    for (int r=0; r<removed.size(); r++) {
21042                        PreferredActivity pa = removed.get(r);
21043                        Slog.w(TAG, "Removing dangling preferred activity: "
21044                                + pa.mPref.mComponent);
21045                        pir.removeFilter(pa);
21046                    }
21047                    mSettings.writePackageRestrictionsLPr(
21048                            mSettings.mPreferredActivities.keyAt(i));
21049                }
21050            }
21051
21052            for (int userId : UserManagerService.getInstance().getUserIds()) {
21053                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21054                    grantPermissionsUserIds = ArrayUtils.appendInt(
21055                            grantPermissionsUserIds, userId);
21056                }
21057            }
21058        }
21059        sUserManager.systemReady();
21060        // If we upgraded grant all default permissions before kicking off.
21061        for (int userId : grantPermissionsUserIds) {
21062            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21063        }
21064
21065        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21066            // If we did not grant default permissions, we preload from this the
21067            // default permission exceptions lazily to ensure we don't hit the
21068            // disk on a new user creation.
21069            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21070        }
21071
21072        // Now that we've scanned all packages, and granted any default
21073        // permissions, ensure permissions are updated. Beware of dragons if you
21074        // try optimizing this.
21075        synchronized (mPackages) {
21076            mPermissionManager.updateAllPermissions(
21077                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21078                    mPermissionCallback);
21079        }
21080
21081        // Kick off any messages waiting for system ready
21082        if (mPostSystemReadyMessages != null) {
21083            for (Message msg : mPostSystemReadyMessages) {
21084                msg.sendToTarget();
21085            }
21086            mPostSystemReadyMessages = null;
21087        }
21088
21089        // Watch for external volumes that come and go over time
21090        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21091        storage.registerListener(mStorageListener);
21092
21093        mInstallerService.systemReady();
21094        mPackageDexOptimizer.systemReady();
21095
21096        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21097                StorageManagerInternal.class);
21098        StorageManagerInternal.addExternalStoragePolicy(
21099                new StorageManagerInternal.ExternalStorageMountPolicy() {
21100            @Override
21101            public int getMountMode(int uid, String packageName) {
21102                if (Process.isIsolated(uid)) {
21103                    return Zygote.MOUNT_EXTERNAL_NONE;
21104                }
21105                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21106                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21107                }
21108                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21109                    return Zygote.MOUNT_EXTERNAL_READ;
21110                }
21111                return Zygote.MOUNT_EXTERNAL_WRITE;
21112            }
21113
21114            @Override
21115            public boolean hasExternalStorage(int uid, String packageName) {
21116                return true;
21117            }
21118        });
21119
21120        // Now that we're mostly running, clean up stale users and apps
21121        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21122        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21123
21124        mPermissionManager.systemReady();
21125
21126        if (mInstantAppResolverConnection != null) {
21127            mContext.registerReceiver(new BroadcastReceiver() {
21128                @Override
21129                public void onReceive(Context context, Intent intent) {
21130                    mInstantAppResolverConnection.optimisticBind();
21131                    mContext.unregisterReceiver(this);
21132                }
21133            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21134        }
21135    }
21136
21137    public void waitForAppDataPrepared() {
21138        if (mPrepareAppDataFuture == null) {
21139            return;
21140        }
21141        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21142        mPrepareAppDataFuture = null;
21143    }
21144
21145    @Override
21146    public boolean isSafeMode() {
21147        // allow instant applications
21148        return mSafeMode;
21149    }
21150
21151    @Override
21152    public boolean hasSystemUidErrors() {
21153        // allow instant applications
21154        return mHasSystemUidErrors;
21155    }
21156
21157    static String arrayToString(int[] array) {
21158        StringBuffer buf = new StringBuffer(128);
21159        buf.append('[');
21160        if (array != null) {
21161            for (int i=0; i<array.length; i++) {
21162                if (i > 0) buf.append(", ");
21163                buf.append(array[i]);
21164            }
21165        }
21166        buf.append(']');
21167        return buf.toString();
21168    }
21169
21170    @Override
21171    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21172            FileDescriptor err, String[] args, ShellCallback callback,
21173            ResultReceiver resultReceiver) {
21174        (new PackageManagerShellCommand(this)).exec(
21175                this, in, out, err, args, callback, resultReceiver);
21176    }
21177
21178    @Override
21179    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21180        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21181
21182        DumpState dumpState = new DumpState();
21183        boolean fullPreferred = false;
21184        boolean checkin = false;
21185
21186        String packageName = null;
21187        ArraySet<String> permissionNames = null;
21188
21189        int opti = 0;
21190        while (opti < args.length) {
21191            String opt = args[opti];
21192            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21193                break;
21194            }
21195            opti++;
21196
21197            if ("-a".equals(opt)) {
21198                // Right now we only know how to print all.
21199            } else if ("-h".equals(opt)) {
21200                pw.println("Package manager dump options:");
21201                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21202                pw.println("    --checkin: dump for a checkin");
21203                pw.println("    -f: print details of intent filters");
21204                pw.println("    -h: print this help");
21205                pw.println("  cmd may be one of:");
21206                pw.println("    l[ibraries]: list known shared libraries");
21207                pw.println("    f[eatures]: list device features");
21208                pw.println("    k[eysets]: print known keysets");
21209                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21210                pw.println("    perm[issions]: dump permissions");
21211                pw.println("    permission [name ...]: dump declaration and use of given permission");
21212                pw.println("    pref[erred]: print preferred package settings");
21213                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21214                pw.println("    prov[iders]: dump content providers");
21215                pw.println("    p[ackages]: dump installed packages");
21216                pw.println("    s[hared-users]: dump shared user IDs");
21217                pw.println("    m[essages]: print collected runtime messages");
21218                pw.println("    v[erifiers]: print package verifier info");
21219                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21220                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21221                pw.println("    version: print database version info");
21222                pw.println("    write: write current settings now");
21223                pw.println("    installs: details about install sessions");
21224                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21225                pw.println("    dexopt: dump dexopt state");
21226                pw.println("    compiler-stats: dump compiler statistics");
21227                pw.println("    service-permissions: dump permissions required by services");
21228                pw.println("    <package.name>: info about given package");
21229                return;
21230            } else if ("--checkin".equals(opt)) {
21231                checkin = true;
21232            } else if ("-f".equals(opt)) {
21233                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21234            } else if ("--proto".equals(opt)) {
21235                dumpProto(fd);
21236                return;
21237            } else {
21238                pw.println("Unknown argument: " + opt + "; use -h for help");
21239            }
21240        }
21241
21242        // Is the caller requesting to dump a particular piece of data?
21243        if (opti < args.length) {
21244            String cmd = args[opti];
21245            opti++;
21246            // Is this a package name?
21247            if ("android".equals(cmd) || cmd.contains(".")) {
21248                packageName = cmd;
21249                // When dumping a single package, we always dump all of its
21250                // filter information since the amount of data will be reasonable.
21251                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21252            } else if ("check-permission".equals(cmd)) {
21253                if (opti >= args.length) {
21254                    pw.println("Error: check-permission missing permission argument");
21255                    return;
21256                }
21257                String perm = args[opti];
21258                opti++;
21259                if (opti >= args.length) {
21260                    pw.println("Error: check-permission missing package argument");
21261                    return;
21262                }
21263
21264                String pkg = args[opti];
21265                opti++;
21266                int user = UserHandle.getUserId(Binder.getCallingUid());
21267                if (opti < args.length) {
21268                    try {
21269                        user = Integer.parseInt(args[opti]);
21270                    } catch (NumberFormatException e) {
21271                        pw.println("Error: check-permission user argument is not a number: "
21272                                + args[opti]);
21273                        return;
21274                    }
21275                }
21276
21277                // Normalize package name to handle renamed packages and static libs
21278                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21279
21280                pw.println(checkPermission(perm, pkg, user));
21281                return;
21282            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21283                dumpState.setDump(DumpState.DUMP_LIBS);
21284            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21285                dumpState.setDump(DumpState.DUMP_FEATURES);
21286            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21287                if (opti >= args.length) {
21288                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21289                            | DumpState.DUMP_SERVICE_RESOLVERS
21290                            | DumpState.DUMP_RECEIVER_RESOLVERS
21291                            | DumpState.DUMP_CONTENT_RESOLVERS);
21292                } else {
21293                    while (opti < args.length) {
21294                        String name = args[opti];
21295                        if ("a".equals(name) || "activity".equals(name)) {
21296                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21297                        } else if ("s".equals(name) || "service".equals(name)) {
21298                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21299                        } else if ("r".equals(name) || "receiver".equals(name)) {
21300                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21301                        } else if ("c".equals(name) || "content".equals(name)) {
21302                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21303                        } else {
21304                            pw.println("Error: unknown resolver table type: " + name);
21305                            return;
21306                        }
21307                        opti++;
21308                    }
21309                }
21310            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21311                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21312            } else if ("permission".equals(cmd)) {
21313                if (opti >= args.length) {
21314                    pw.println("Error: permission requires permission name");
21315                    return;
21316                }
21317                permissionNames = new ArraySet<>();
21318                while (opti < args.length) {
21319                    permissionNames.add(args[opti]);
21320                    opti++;
21321                }
21322                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21323                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21324            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21325                dumpState.setDump(DumpState.DUMP_PREFERRED);
21326            } else if ("preferred-xml".equals(cmd)) {
21327                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21328                if (opti < args.length && "--full".equals(args[opti])) {
21329                    fullPreferred = true;
21330                    opti++;
21331                }
21332            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21333                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21334            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21335                dumpState.setDump(DumpState.DUMP_PACKAGES);
21336            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21337                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21338            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21339                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21340            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21341                dumpState.setDump(DumpState.DUMP_MESSAGES);
21342            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21343                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21344            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21345                    || "intent-filter-verifiers".equals(cmd)) {
21346                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21347            } else if ("version".equals(cmd)) {
21348                dumpState.setDump(DumpState.DUMP_VERSION);
21349            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21350                dumpState.setDump(DumpState.DUMP_KEYSETS);
21351            } else if ("installs".equals(cmd)) {
21352                dumpState.setDump(DumpState.DUMP_INSTALLS);
21353            } else if ("frozen".equals(cmd)) {
21354                dumpState.setDump(DumpState.DUMP_FROZEN);
21355            } else if ("volumes".equals(cmd)) {
21356                dumpState.setDump(DumpState.DUMP_VOLUMES);
21357            } else if ("dexopt".equals(cmd)) {
21358                dumpState.setDump(DumpState.DUMP_DEXOPT);
21359            } else if ("compiler-stats".equals(cmd)) {
21360                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21361            } else if ("changes".equals(cmd)) {
21362                dumpState.setDump(DumpState.DUMP_CHANGES);
21363            } else if ("service-permissions".equals(cmd)) {
21364                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21365            } else if ("write".equals(cmd)) {
21366                synchronized (mPackages) {
21367                    mSettings.writeLPr();
21368                    pw.println("Settings written.");
21369                    return;
21370                }
21371            }
21372        }
21373
21374        if (checkin) {
21375            pw.println("vers,1");
21376        }
21377
21378        // reader
21379        synchronized (mPackages) {
21380            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21381                if (!checkin) {
21382                    if (dumpState.onTitlePrinted())
21383                        pw.println();
21384                    pw.println("Database versions:");
21385                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21386                }
21387            }
21388
21389            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21390                if (!checkin) {
21391                    if (dumpState.onTitlePrinted())
21392                        pw.println();
21393                    pw.println("Verifiers:");
21394                    pw.print("  Required: ");
21395                    pw.print(mRequiredVerifierPackage);
21396                    pw.print(" (uid=");
21397                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21398                            UserHandle.USER_SYSTEM));
21399                    pw.println(")");
21400                } else if (mRequiredVerifierPackage != null) {
21401                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21402                    pw.print(",");
21403                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21404                            UserHandle.USER_SYSTEM));
21405                }
21406            }
21407
21408            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21409                    packageName == null) {
21410                if (mIntentFilterVerifierComponent != null) {
21411                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21412                    if (!checkin) {
21413                        if (dumpState.onTitlePrinted())
21414                            pw.println();
21415                        pw.println("Intent Filter Verifier:");
21416                        pw.print("  Using: ");
21417                        pw.print(verifierPackageName);
21418                        pw.print(" (uid=");
21419                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21420                                UserHandle.USER_SYSTEM));
21421                        pw.println(")");
21422                    } else if (verifierPackageName != null) {
21423                        pw.print("ifv,"); pw.print(verifierPackageName);
21424                        pw.print(",");
21425                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21426                                UserHandle.USER_SYSTEM));
21427                    }
21428                } else {
21429                    pw.println();
21430                    pw.println("No Intent Filter Verifier available!");
21431                }
21432            }
21433
21434            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21435                boolean printedHeader = false;
21436                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21437                while (it.hasNext()) {
21438                    String libName = it.next();
21439                    LongSparseArray<SharedLibraryEntry> versionedLib
21440                            = mSharedLibraries.get(libName);
21441                    if (versionedLib == null) {
21442                        continue;
21443                    }
21444                    final int versionCount = versionedLib.size();
21445                    for (int i = 0; i < versionCount; i++) {
21446                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21447                        if (!checkin) {
21448                            if (!printedHeader) {
21449                                if (dumpState.onTitlePrinted())
21450                                    pw.println();
21451                                pw.println("Libraries:");
21452                                printedHeader = true;
21453                            }
21454                            pw.print("  ");
21455                        } else {
21456                            pw.print("lib,");
21457                        }
21458                        pw.print(libEntry.info.getName());
21459                        if (libEntry.info.isStatic()) {
21460                            pw.print(" version=" + libEntry.info.getLongVersion());
21461                        }
21462                        if (!checkin) {
21463                            pw.print(" -> ");
21464                        }
21465                        if (libEntry.path != null) {
21466                            pw.print(" (jar) ");
21467                            pw.print(libEntry.path);
21468                        } else {
21469                            pw.print(" (apk) ");
21470                            pw.print(libEntry.apk);
21471                        }
21472                        pw.println();
21473                    }
21474                }
21475            }
21476
21477            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21478                if (dumpState.onTitlePrinted())
21479                    pw.println();
21480                if (!checkin) {
21481                    pw.println("Features:");
21482                }
21483
21484                synchronized (mAvailableFeatures) {
21485                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21486                        if (checkin) {
21487                            pw.print("feat,");
21488                            pw.print(feat.name);
21489                            pw.print(",");
21490                            pw.println(feat.version);
21491                        } else {
21492                            pw.print("  ");
21493                            pw.print(feat.name);
21494                            if (feat.version > 0) {
21495                                pw.print(" version=");
21496                                pw.print(feat.version);
21497                            }
21498                            pw.println();
21499                        }
21500                    }
21501                }
21502            }
21503
21504            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21505                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21506                        : "Activity Resolver Table:", "  ", packageName,
21507                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21508                    dumpState.setTitlePrinted(true);
21509                }
21510            }
21511            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21512                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21513                        : "Receiver Resolver Table:", "  ", packageName,
21514                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21515                    dumpState.setTitlePrinted(true);
21516                }
21517            }
21518            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21519                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21520                        : "Service Resolver Table:", "  ", packageName,
21521                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21522                    dumpState.setTitlePrinted(true);
21523                }
21524            }
21525            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21526                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21527                        : "Provider Resolver Table:", "  ", packageName,
21528                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21529                    dumpState.setTitlePrinted(true);
21530                }
21531            }
21532
21533            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21534                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21535                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21536                    int user = mSettings.mPreferredActivities.keyAt(i);
21537                    if (pir.dump(pw,
21538                            dumpState.getTitlePrinted()
21539                                ? "\nPreferred Activities User " + user + ":"
21540                                : "Preferred Activities User " + user + ":", "  ",
21541                            packageName, true, false)) {
21542                        dumpState.setTitlePrinted(true);
21543                    }
21544                }
21545            }
21546
21547            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21548                pw.flush();
21549                FileOutputStream fout = new FileOutputStream(fd);
21550                BufferedOutputStream str = new BufferedOutputStream(fout);
21551                XmlSerializer serializer = new FastXmlSerializer();
21552                try {
21553                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21554                    serializer.startDocument(null, true);
21555                    serializer.setFeature(
21556                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21557                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21558                    serializer.endDocument();
21559                    serializer.flush();
21560                } catch (IllegalArgumentException e) {
21561                    pw.println("Failed writing: " + e);
21562                } catch (IllegalStateException e) {
21563                    pw.println("Failed writing: " + e);
21564                } catch (IOException e) {
21565                    pw.println("Failed writing: " + e);
21566                }
21567            }
21568
21569            if (!checkin
21570                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21571                    && packageName == null) {
21572                pw.println();
21573                int count = mSettings.mPackages.size();
21574                if (count == 0) {
21575                    pw.println("No applications!");
21576                    pw.println();
21577                } else {
21578                    final String prefix = "  ";
21579                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21580                    if (allPackageSettings.size() == 0) {
21581                        pw.println("No domain preferred apps!");
21582                        pw.println();
21583                    } else {
21584                        pw.println("App verification status:");
21585                        pw.println();
21586                        count = 0;
21587                        for (PackageSetting ps : allPackageSettings) {
21588                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21589                            if (ivi == null || ivi.getPackageName() == null) continue;
21590                            pw.println(prefix + "Package: " + ivi.getPackageName());
21591                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21592                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21593                            pw.println();
21594                            count++;
21595                        }
21596                        if (count == 0) {
21597                            pw.println(prefix + "No app verification established.");
21598                            pw.println();
21599                        }
21600                        for (int userId : sUserManager.getUserIds()) {
21601                            pw.println("App linkages for user " + userId + ":");
21602                            pw.println();
21603                            count = 0;
21604                            for (PackageSetting ps : allPackageSettings) {
21605                                final long status = ps.getDomainVerificationStatusForUser(userId);
21606                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21607                                        && !DEBUG_DOMAIN_VERIFICATION) {
21608                                    continue;
21609                                }
21610                                pw.println(prefix + "Package: " + ps.name);
21611                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21612                                String statusStr = IntentFilterVerificationInfo.
21613                                        getStatusStringFromValue(status);
21614                                pw.println(prefix + "Status:  " + statusStr);
21615                                pw.println();
21616                                count++;
21617                            }
21618                            if (count == 0) {
21619                                pw.println(prefix + "No configured app linkages.");
21620                                pw.println();
21621                            }
21622                        }
21623                    }
21624                }
21625            }
21626
21627            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21628                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21629            }
21630
21631            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21632                boolean printedSomething = false;
21633                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21634                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21635                        continue;
21636                    }
21637                    if (!printedSomething) {
21638                        if (dumpState.onTitlePrinted())
21639                            pw.println();
21640                        pw.println("Registered ContentProviders:");
21641                        printedSomething = true;
21642                    }
21643                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21644                    pw.print("    "); pw.println(p.toString());
21645                }
21646                printedSomething = false;
21647                for (Map.Entry<String, PackageParser.Provider> entry :
21648                        mProvidersByAuthority.entrySet()) {
21649                    PackageParser.Provider p = entry.getValue();
21650                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21651                        continue;
21652                    }
21653                    if (!printedSomething) {
21654                        if (dumpState.onTitlePrinted())
21655                            pw.println();
21656                        pw.println("ContentProvider Authorities:");
21657                        printedSomething = true;
21658                    }
21659                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21660                    pw.print("    "); pw.println(p.toString());
21661                    if (p.info != null && p.info.applicationInfo != null) {
21662                        final String appInfo = p.info.applicationInfo.toString();
21663                        pw.print("      applicationInfo="); pw.println(appInfo);
21664                    }
21665                }
21666            }
21667
21668            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21669                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21670            }
21671
21672            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21673                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21674            }
21675
21676            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21677                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21678            }
21679
21680            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21681                if (dumpState.onTitlePrinted()) pw.println();
21682                pw.println("Package Changes:");
21683                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21684                final int K = mChangedPackages.size();
21685                for (int i = 0; i < K; i++) {
21686                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21687                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21688                    final int N = changes.size();
21689                    if (N == 0) {
21690                        pw.print("    "); pw.println("No packages changed");
21691                    } else {
21692                        for (int j = 0; j < N; j++) {
21693                            final String pkgName = changes.valueAt(j);
21694                            final int sequenceNumber = changes.keyAt(j);
21695                            pw.print("    ");
21696                            pw.print("seq=");
21697                            pw.print(sequenceNumber);
21698                            pw.print(", package=");
21699                            pw.println(pkgName);
21700                        }
21701                    }
21702                }
21703            }
21704
21705            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21706                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21707            }
21708
21709            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21710                // XXX should handle packageName != null by dumping only install data that
21711                // the given package is involved with.
21712                if (dumpState.onTitlePrinted()) pw.println();
21713
21714                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21715                ipw.println();
21716                ipw.println("Frozen packages:");
21717                ipw.increaseIndent();
21718                if (mFrozenPackages.size() == 0) {
21719                    ipw.println("(none)");
21720                } else {
21721                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21722                        ipw.println(mFrozenPackages.valueAt(i));
21723                    }
21724                }
21725                ipw.decreaseIndent();
21726            }
21727
21728            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21729                if (dumpState.onTitlePrinted()) pw.println();
21730
21731                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21732                ipw.println();
21733                ipw.println("Loaded volumes:");
21734                ipw.increaseIndent();
21735                if (mLoadedVolumes.size() == 0) {
21736                    ipw.println("(none)");
21737                } else {
21738                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21739                        ipw.println(mLoadedVolumes.valueAt(i));
21740                    }
21741                }
21742                ipw.decreaseIndent();
21743            }
21744
21745            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21746                    && packageName == null) {
21747                if (dumpState.onTitlePrinted()) pw.println();
21748                pw.println("Service permissions:");
21749
21750                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21751                while (filterIterator.hasNext()) {
21752                    final ServiceIntentInfo info = filterIterator.next();
21753                    final ServiceInfo serviceInfo = info.service.info;
21754                    final String permission = serviceInfo.permission;
21755                    if (permission != null) {
21756                        pw.print("    ");
21757                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21758                        pw.print(": ");
21759                        pw.println(permission);
21760                    }
21761                }
21762            }
21763
21764            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21765                if (dumpState.onTitlePrinted()) pw.println();
21766                dumpDexoptStateLPr(pw, packageName);
21767            }
21768
21769            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21770                if (dumpState.onTitlePrinted()) pw.println();
21771                dumpCompilerStatsLPr(pw, packageName);
21772            }
21773
21774            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21775                if (dumpState.onTitlePrinted()) pw.println();
21776                mSettings.dumpReadMessagesLPr(pw, dumpState);
21777
21778                pw.println();
21779                pw.println("Package warning messages:");
21780                dumpCriticalInfo(pw, null);
21781            }
21782
21783            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21784                dumpCriticalInfo(pw, "msg,");
21785            }
21786        }
21787
21788        // PackageInstaller should be called outside of mPackages lock
21789        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21790            // XXX should handle packageName != null by dumping only install data that
21791            // the given package is involved with.
21792            if (dumpState.onTitlePrinted()) pw.println();
21793            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21794        }
21795    }
21796
21797    private void dumpProto(FileDescriptor fd) {
21798        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21799
21800        synchronized (mPackages) {
21801            final long requiredVerifierPackageToken =
21802                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21803            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21804            proto.write(
21805                    PackageServiceDumpProto.PackageShortProto.UID,
21806                    getPackageUid(
21807                            mRequiredVerifierPackage,
21808                            MATCH_DEBUG_TRIAGED_MISSING,
21809                            UserHandle.USER_SYSTEM));
21810            proto.end(requiredVerifierPackageToken);
21811
21812            if (mIntentFilterVerifierComponent != null) {
21813                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21814                final long verifierPackageToken =
21815                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21816                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21817                proto.write(
21818                        PackageServiceDumpProto.PackageShortProto.UID,
21819                        getPackageUid(
21820                                verifierPackageName,
21821                                MATCH_DEBUG_TRIAGED_MISSING,
21822                                UserHandle.USER_SYSTEM));
21823                proto.end(verifierPackageToken);
21824            }
21825
21826            dumpSharedLibrariesProto(proto);
21827            dumpFeaturesProto(proto);
21828            mSettings.dumpPackagesProto(proto);
21829            mSettings.dumpSharedUsersProto(proto);
21830            dumpCriticalInfo(proto);
21831        }
21832        proto.flush();
21833    }
21834
21835    private void dumpFeaturesProto(ProtoOutputStream proto) {
21836        synchronized (mAvailableFeatures) {
21837            final int count = mAvailableFeatures.size();
21838            for (int i = 0; i < count; i++) {
21839                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21840            }
21841        }
21842    }
21843
21844    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21845        final int count = mSharedLibraries.size();
21846        for (int i = 0; i < count; i++) {
21847            final String libName = mSharedLibraries.keyAt(i);
21848            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21849            if (versionedLib == null) {
21850                continue;
21851            }
21852            final int versionCount = versionedLib.size();
21853            for (int j = 0; j < versionCount; j++) {
21854                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21855                final long sharedLibraryToken =
21856                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21857                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21858                final boolean isJar = (libEntry.path != null);
21859                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21860                if (isJar) {
21861                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21862                } else {
21863                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21864                }
21865                proto.end(sharedLibraryToken);
21866            }
21867        }
21868    }
21869
21870    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21871        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21872        ipw.println();
21873        ipw.println("Dexopt state:");
21874        ipw.increaseIndent();
21875        Collection<PackageParser.Package> packages = null;
21876        if (packageName != null) {
21877            PackageParser.Package targetPackage = mPackages.get(packageName);
21878            if (targetPackage != null) {
21879                packages = Collections.singletonList(targetPackage);
21880            } else {
21881                ipw.println("Unable to find package: " + packageName);
21882                return;
21883            }
21884        } else {
21885            packages = mPackages.values();
21886        }
21887
21888        for (PackageParser.Package pkg : packages) {
21889            ipw.println("[" + pkg.packageName + "]");
21890            ipw.increaseIndent();
21891            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21892                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21893            ipw.decreaseIndent();
21894        }
21895    }
21896
21897    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21898        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21899        ipw.println();
21900        ipw.println("Compiler stats:");
21901        ipw.increaseIndent();
21902        Collection<PackageParser.Package> packages = null;
21903        if (packageName != null) {
21904            PackageParser.Package targetPackage = mPackages.get(packageName);
21905            if (targetPackage != null) {
21906                packages = Collections.singletonList(targetPackage);
21907            } else {
21908                ipw.println("Unable to find package: " + packageName);
21909                return;
21910            }
21911        } else {
21912            packages = mPackages.values();
21913        }
21914
21915        for (PackageParser.Package pkg : packages) {
21916            ipw.println("[" + pkg.packageName + "]");
21917            ipw.increaseIndent();
21918
21919            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21920            if (stats == null) {
21921                ipw.println("(No recorded stats)");
21922            } else {
21923                stats.dump(ipw);
21924            }
21925            ipw.decreaseIndent();
21926        }
21927    }
21928
21929    private String dumpDomainString(String packageName) {
21930        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21931                .getList();
21932        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21933
21934        ArraySet<String> result = new ArraySet<>();
21935        if (iviList.size() > 0) {
21936            for (IntentFilterVerificationInfo ivi : iviList) {
21937                for (String host : ivi.getDomains()) {
21938                    result.add(host);
21939                }
21940            }
21941        }
21942        if (filters != null && filters.size() > 0) {
21943            for (IntentFilter filter : filters) {
21944                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21945                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21946                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21947                    result.addAll(filter.getHostsList());
21948                }
21949            }
21950        }
21951
21952        StringBuilder sb = new StringBuilder(result.size() * 16);
21953        for (String domain : result) {
21954            if (sb.length() > 0) sb.append(" ");
21955            sb.append(domain);
21956        }
21957        return sb.toString();
21958    }
21959
21960    // ------- apps on sdcard specific code -------
21961    static final boolean DEBUG_SD_INSTALL = false;
21962
21963    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21964
21965    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21966
21967    private boolean mMediaMounted = false;
21968
21969    static String getEncryptKey() {
21970        try {
21971            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21972                    SD_ENCRYPTION_KEYSTORE_NAME);
21973            if (sdEncKey == null) {
21974                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21975                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21976                if (sdEncKey == null) {
21977                    Slog.e(TAG, "Failed to create encryption keys");
21978                    return null;
21979                }
21980            }
21981            return sdEncKey;
21982        } catch (NoSuchAlgorithmException nsae) {
21983            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21984            return null;
21985        } catch (IOException ioe) {
21986            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21987            return null;
21988        }
21989    }
21990
21991    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21992            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21993        final int size = infos.size();
21994        final String[] packageNames = new String[size];
21995        final int[] packageUids = new int[size];
21996        for (int i = 0; i < size; i++) {
21997            final ApplicationInfo info = infos.get(i);
21998            packageNames[i] = info.packageName;
21999            packageUids[i] = info.uid;
22000        }
22001        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22002                finishedReceiver);
22003    }
22004
22005    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22006            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22007        sendResourcesChangedBroadcast(mediaStatus, replacing,
22008                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22009    }
22010
22011    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22012            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22013        int size = pkgList.length;
22014        if (size > 0) {
22015            // Send broadcasts here
22016            Bundle extras = new Bundle();
22017            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22018            if (uidArr != null) {
22019                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22020            }
22021            if (replacing) {
22022                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22023            }
22024            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22025                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22026            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22027        }
22028    }
22029
22030    private void loadPrivatePackages(final VolumeInfo vol) {
22031        mHandler.post(new Runnable() {
22032            @Override
22033            public void run() {
22034                loadPrivatePackagesInner(vol);
22035            }
22036        });
22037    }
22038
22039    private void loadPrivatePackagesInner(VolumeInfo vol) {
22040        final String volumeUuid = vol.fsUuid;
22041        if (TextUtils.isEmpty(volumeUuid)) {
22042            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22043            return;
22044        }
22045
22046        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22047        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22048        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22049
22050        final VersionInfo ver;
22051        final List<PackageSetting> packages;
22052        synchronized (mPackages) {
22053            ver = mSettings.findOrCreateVersion(volumeUuid);
22054            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22055        }
22056
22057        for (PackageSetting ps : packages) {
22058            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22059            synchronized (mInstallLock) {
22060                final PackageParser.Package pkg;
22061                try {
22062                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22063                    loaded.add(pkg.applicationInfo);
22064
22065                } catch (PackageManagerException e) {
22066                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22067                }
22068
22069                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22070                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22071                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22072                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22073                }
22074            }
22075        }
22076
22077        // Reconcile app data for all started/unlocked users
22078        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22079        final UserManager um = mContext.getSystemService(UserManager.class);
22080        UserManagerInternal umInternal = getUserManagerInternal();
22081        for (UserInfo user : um.getUsers()) {
22082            final int flags;
22083            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22084                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22085            } else if (umInternal.isUserRunning(user.id)) {
22086                flags = StorageManager.FLAG_STORAGE_DE;
22087            } else {
22088                continue;
22089            }
22090
22091            try {
22092                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22093                synchronized (mInstallLock) {
22094                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22095                }
22096            } catch (IllegalStateException e) {
22097                // Device was probably ejected, and we'll process that event momentarily
22098                Slog.w(TAG, "Failed to prepare storage: " + e);
22099            }
22100        }
22101
22102        synchronized (mPackages) {
22103            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22104            if (sdkUpdated) {
22105                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22106                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22107            }
22108            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22109                    mPermissionCallback);
22110
22111            // Yay, everything is now upgraded
22112            ver.forceCurrent();
22113
22114            mSettings.writeLPr();
22115        }
22116
22117        for (PackageFreezer freezer : freezers) {
22118            freezer.close();
22119        }
22120
22121        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22122        sendResourcesChangedBroadcast(true, false, loaded, null);
22123        mLoadedVolumes.add(vol.getId());
22124    }
22125
22126    private void unloadPrivatePackages(final VolumeInfo vol) {
22127        mHandler.post(new Runnable() {
22128            @Override
22129            public void run() {
22130                unloadPrivatePackagesInner(vol);
22131            }
22132        });
22133    }
22134
22135    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22136        final String volumeUuid = vol.fsUuid;
22137        if (TextUtils.isEmpty(volumeUuid)) {
22138            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22139            return;
22140        }
22141
22142        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22143        synchronized (mInstallLock) {
22144        synchronized (mPackages) {
22145            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22146            for (PackageSetting ps : packages) {
22147                if (ps.pkg == null) continue;
22148
22149                final ApplicationInfo info = ps.pkg.applicationInfo;
22150                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22151                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22152
22153                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22154                        "unloadPrivatePackagesInner")) {
22155                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22156                            false, null)) {
22157                        unloaded.add(info);
22158                    } else {
22159                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22160                    }
22161                }
22162
22163                // Try very hard to release any references to this package
22164                // so we don't risk the system server being killed due to
22165                // open FDs
22166                AttributeCache.instance().removePackage(ps.name);
22167            }
22168
22169            mSettings.writeLPr();
22170        }
22171        }
22172
22173        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22174        sendResourcesChangedBroadcast(false, false, unloaded, null);
22175        mLoadedVolumes.remove(vol.getId());
22176
22177        // Try very hard to release any references to this path so we don't risk
22178        // the system server being killed due to open FDs
22179        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22180
22181        for (int i = 0; i < 3; i++) {
22182            System.gc();
22183            System.runFinalization();
22184        }
22185    }
22186
22187    private void assertPackageKnown(String volumeUuid, String packageName)
22188            throws PackageManagerException {
22189        synchronized (mPackages) {
22190            // Normalize package name to handle renamed packages
22191            packageName = normalizePackageNameLPr(packageName);
22192
22193            final PackageSetting ps = mSettings.mPackages.get(packageName);
22194            if (ps == null) {
22195                throw new PackageManagerException("Package " + packageName + " is unknown");
22196            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22197                throw new PackageManagerException(
22198                        "Package " + packageName + " found on unknown volume " + volumeUuid
22199                                + "; expected volume " + ps.volumeUuid);
22200            }
22201        }
22202    }
22203
22204    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22205            throws PackageManagerException {
22206        synchronized (mPackages) {
22207            // Normalize package name to handle renamed packages
22208            packageName = normalizePackageNameLPr(packageName);
22209
22210            final PackageSetting ps = mSettings.mPackages.get(packageName);
22211            if (ps == null) {
22212                throw new PackageManagerException("Package " + packageName + " is unknown");
22213            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22214                throw new PackageManagerException(
22215                        "Package " + packageName + " found on unknown volume " + volumeUuid
22216                                + "; expected volume " + ps.volumeUuid);
22217            } else if (!ps.getInstalled(userId)) {
22218                throw new PackageManagerException(
22219                        "Package " + packageName + " not installed for user " + userId);
22220            }
22221        }
22222    }
22223
22224    private List<String> collectAbsoluteCodePaths() {
22225        synchronized (mPackages) {
22226            List<String> codePaths = new ArrayList<>();
22227            final int packageCount = mSettings.mPackages.size();
22228            for (int i = 0; i < packageCount; i++) {
22229                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22230                codePaths.add(ps.codePath.getAbsolutePath());
22231            }
22232            return codePaths;
22233        }
22234    }
22235
22236    /**
22237     * Examine all apps present on given mounted volume, and destroy apps that
22238     * aren't expected, either due to uninstallation or reinstallation on
22239     * another volume.
22240     */
22241    private void reconcileApps(String volumeUuid) {
22242        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22243        List<File> filesToDelete = null;
22244
22245        final File[] files = FileUtils.listFilesOrEmpty(
22246                Environment.getDataAppDirectory(volumeUuid));
22247        for (File file : files) {
22248            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22249                    && !PackageInstallerService.isStageName(file.getName());
22250            if (!isPackage) {
22251                // Ignore entries which are not packages
22252                continue;
22253            }
22254
22255            String absolutePath = file.getAbsolutePath();
22256
22257            boolean pathValid = false;
22258            final int absoluteCodePathCount = absoluteCodePaths.size();
22259            for (int i = 0; i < absoluteCodePathCount; i++) {
22260                String absoluteCodePath = absoluteCodePaths.get(i);
22261                if (absolutePath.startsWith(absoluteCodePath)) {
22262                    pathValid = true;
22263                    break;
22264                }
22265            }
22266
22267            if (!pathValid) {
22268                if (filesToDelete == null) {
22269                    filesToDelete = new ArrayList<>();
22270                }
22271                filesToDelete.add(file);
22272            }
22273        }
22274
22275        if (filesToDelete != null) {
22276            final int fileToDeleteCount = filesToDelete.size();
22277            for (int i = 0; i < fileToDeleteCount; i++) {
22278                File fileToDelete = filesToDelete.get(i);
22279                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22280                synchronized (mInstallLock) {
22281                    removeCodePathLI(fileToDelete);
22282                }
22283            }
22284        }
22285    }
22286
22287    /**
22288     * Reconcile all app data for the given user.
22289     * <p>
22290     * Verifies that directories exist and that ownership and labeling is
22291     * correct for all installed apps on all mounted volumes.
22292     */
22293    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22294        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22295        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22296            final String volumeUuid = vol.getFsUuid();
22297            synchronized (mInstallLock) {
22298                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22299            }
22300        }
22301    }
22302
22303    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22304            boolean migrateAppData) {
22305        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22306    }
22307
22308    /**
22309     * Reconcile all app data on given mounted volume.
22310     * <p>
22311     * Destroys app data that isn't expected, either due to uninstallation or
22312     * reinstallation on another volume.
22313     * <p>
22314     * Verifies that directories exist and that ownership and labeling is
22315     * correct for all installed apps.
22316     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22317     */
22318    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22319            boolean migrateAppData, boolean onlyCoreApps) {
22320        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22321                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22322        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22323
22324        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22325        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22326
22327        // First look for stale data that doesn't belong, and check if things
22328        // have changed since we did our last restorecon
22329        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22330            if (StorageManager.isFileEncryptedNativeOrEmulated()
22331                    && !StorageManager.isUserKeyUnlocked(userId)) {
22332                throw new RuntimeException(
22333                        "Yikes, someone asked us to reconcile CE storage while " + userId
22334                                + " was still locked; this would have caused massive data loss!");
22335            }
22336
22337            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22338            for (File file : files) {
22339                final String packageName = file.getName();
22340                try {
22341                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22342                } catch (PackageManagerException e) {
22343                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22344                    try {
22345                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22346                                StorageManager.FLAG_STORAGE_CE, 0);
22347                    } catch (InstallerException e2) {
22348                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22349                    }
22350                }
22351            }
22352        }
22353        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22354            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22355            for (File file : files) {
22356                final String packageName = file.getName();
22357                try {
22358                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22359                } catch (PackageManagerException e) {
22360                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22361                    try {
22362                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22363                                StorageManager.FLAG_STORAGE_DE, 0);
22364                    } catch (InstallerException e2) {
22365                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22366                    }
22367                }
22368            }
22369        }
22370
22371        // Ensure that data directories are ready to roll for all packages
22372        // installed for this volume and user
22373        final List<PackageSetting> packages;
22374        synchronized (mPackages) {
22375            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22376        }
22377        int preparedCount = 0;
22378        for (PackageSetting ps : packages) {
22379            final String packageName = ps.name;
22380            if (ps.pkg == null) {
22381                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22382                // TODO: might be due to legacy ASEC apps; we should circle back
22383                // and reconcile again once they're scanned
22384                continue;
22385            }
22386            // Skip non-core apps if requested
22387            if (onlyCoreApps && !ps.pkg.coreApp) {
22388                result.add(packageName);
22389                continue;
22390            }
22391
22392            if (ps.getInstalled(userId)) {
22393                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22394                preparedCount++;
22395            }
22396        }
22397
22398        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22399        return result;
22400    }
22401
22402    /**
22403     * Prepare app data for the given app just after it was installed or
22404     * upgraded. This method carefully only touches users that it's installed
22405     * for, and it forces a restorecon to handle any seinfo changes.
22406     * <p>
22407     * Verifies that directories exist and that ownership and labeling is
22408     * correct for all installed apps. If there is an ownership mismatch, it
22409     * will try recovering system apps by wiping data; third-party app data is
22410     * left intact.
22411     * <p>
22412     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22413     */
22414    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22415        final PackageSetting ps;
22416        synchronized (mPackages) {
22417            ps = mSettings.mPackages.get(pkg.packageName);
22418            mSettings.writeKernelMappingLPr(ps);
22419        }
22420
22421        final UserManager um = mContext.getSystemService(UserManager.class);
22422        UserManagerInternal umInternal = getUserManagerInternal();
22423        for (UserInfo user : um.getUsers()) {
22424            final int flags;
22425            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22426                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22427            } else if (umInternal.isUserRunning(user.id)) {
22428                flags = StorageManager.FLAG_STORAGE_DE;
22429            } else {
22430                continue;
22431            }
22432
22433            if (ps.getInstalled(user.id)) {
22434                // TODO: when user data is locked, mark that we're still dirty
22435                prepareAppDataLIF(pkg, user.id, flags);
22436            }
22437        }
22438    }
22439
22440    /**
22441     * Prepare app data for the given app.
22442     * <p>
22443     * Verifies that directories exist and that ownership and labeling is
22444     * correct for all installed apps. If there is an ownership mismatch, this
22445     * will try recovering system apps by wiping data; third-party app data is
22446     * left intact.
22447     */
22448    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22449        if (pkg == null) {
22450            Slog.wtf(TAG, "Package was null!", new Throwable());
22451            return;
22452        }
22453        prepareAppDataLeafLIF(pkg, userId, flags);
22454        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22455        for (int i = 0; i < childCount; i++) {
22456            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22457        }
22458    }
22459
22460    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22461            boolean maybeMigrateAppData) {
22462        prepareAppDataLIF(pkg, userId, flags);
22463
22464        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22465            // We may have just shuffled around app data directories, so
22466            // prepare them one more time
22467            prepareAppDataLIF(pkg, userId, flags);
22468        }
22469    }
22470
22471    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22472        if (DEBUG_APP_DATA) {
22473            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22474                    + Integer.toHexString(flags));
22475        }
22476
22477        final PackageSetting ps;
22478        synchronized (mPackages) {
22479            ps = mSettings.mPackages.get(pkg.packageName);
22480        }
22481        final String volumeUuid = pkg.volumeUuid;
22482        final String packageName = pkg.packageName;
22483        final ApplicationInfo app = (ps == null)
22484                ? pkg.applicationInfo
22485                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22486
22487        final int appId = UserHandle.getAppId(app.uid);
22488
22489        Preconditions.checkNotNull(app.seInfo);
22490
22491        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22492        long ceDataInode = -1;
22493        try {
22494            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22495                    appId, seInfo, app.targetSdkVersion);
22496        } catch (InstallerException e) {
22497            if (app.isSystemApp()) {
22498                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22499                        + ", but trying to recover: " + e);
22500                destroyAppDataLeafLIF(pkg, userId, flags);
22501                try {
22502                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22503                            appId, seInfo, app.targetSdkVersion);
22504                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22505                } catch (InstallerException e2) {
22506                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22507                }
22508            } else {
22509                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22510            }
22511        }
22512        // Prepare the application profiles only for upgrades and first boot (so that we don't
22513        // repeat the same operation at each boot).
22514        // We only have to cover the upgrade and first boot here because for app installs we
22515        // prepare the profiles before invoking dexopt (in installPackageLI).
22516        //
22517        // We also have to cover non system users because we do not call the usual install package
22518        // methods for them.
22519        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22520            mArtManagerService.prepareAppProfiles(pkg, userId);
22521        }
22522
22523        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22524            // TODO: mark this structure as dirty so we persist it!
22525            synchronized (mPackages) {
22526                if (ps != null) {
22527                    ps.setCeDataInode(ceDataInode, userId);
22528                }
22529            }
22530        }
22531
22532        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22533    }
22534
22535    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22536        if (pkg == null) {
22537            Slog.wtf(TAG, "Package was null!", new Throwable());
22538            return;
22539        }
22540        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22541        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22542        for (int i = 0; i < childCount; i++) {
22543            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22544        }
22545    }
22546
22547    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22548        final String volumeUuid = pkg.volumeUuid;
22549        final String packageName = pkg.packageName;
22550        final ApplicationInfo app = pkg.applicationInfo;
22551
22552        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22553            // Create a native library symlink only if we have native libraries
22554            // and if the native libraries are 32 bit libraries. We do not provide
22555            // this symlink for 64 bit libraries.
22556            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22557                final String nativeLibPath = app.nativeLibraryDir;
22558                try {
22559                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22560                            nativeLibPath, userId);
22561                } catch (InstallerException e) {
22562                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22563                }
22564            }
22565        }
22566    }
22567
22568    /**
22569     * For system apps on non-FBE devices, this method migrates any existing
22570     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22571     * requested by the app.
22572     */
22573    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22574        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22575                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22576            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22577                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22578            try {
22579                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22580                        storageTarget);
22581            } catch (InstallerException e) {
22582                logCriticalInfo(Log.WARN,
22583                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22584            }
22585            return true;
22586        } else {
22587            return false;
22588        }
22589    }
22590
22591    public PackageFreezer freezePackage(String packageName, String killReason) {
22592        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22593    }
22594
22595    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22596        return new PackageFreezer(packageName, userId, killReason);
22597    }
22598
22599    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22600            String killReason) {
22601        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22602    }
22603
22604    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22605            String killReason) {
22606        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22607            return new PackageFreezer();
22608        } else {
22609            return freezePackage(packageName, userId, killReason);
22610        }
22611    }
22612
22613    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22614            String killReason) {
22615        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22616    }
22617
22618    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22619            String killReason) {
22620        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22621            return new PackageFreezer();
22622        } else {
22623            return freezePackage(packageName, userId, killReason);
22624        }
22625    }
22626
22627    /**
22628     * Class that freezes and kills the given package upon creation, and
22629     * unfreezes it upon closing. This is typically used when doing surgery on
22630     * app code/data to prevent the app from running while you're working.
22631     */
22632    private class PackageFreezer implements AutoCloseable {
22633        private final String mPackageName;
22634        private final PackageFreezer[] mChildren;
22635
22636        private final boolean mWeFroze;
22637
22638        private final AtomicBoolean mClosed = new AtomicBoolean();
22639        private final CloseGuard mCloseGuard = CloseGuard.get();
22640
22641        /**
22642         * Create and return a stub freezer that doesn't actually do anything,
22643         * typically used when someone requested
22644         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22645         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22646         */
22647        public PackageFreezer() {
22648            mPackageName = null;
22649            mChildren = null;
22650            mWeFroze = false;
22651            mCloseGuard.open("close");
22652        }
22653
22654        public PackageFreezer(String packageName, int userId, String killReason) {
22655            synchronized (mPackages) {
22656                mPackageName = packageName;
22657                mWeFroze = mFrozenPackages.add(mPackageName);
22658
22659                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22660                if (ps != null) {
22661                    killApplication(ps.name, ps.appId, userId, killReason);
22662                }
22663
22664                final PackageParser.Package p = mPackages.get(packageName);
22665                if (p != null && p.childPackages != null) {
22666                    final int N = p.childPackages.size();
22667                    mChildren = new PackageFreezer[N];
22668                    for (int i = 0; i < N; i++) {
22669                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22670                                userId, killReason);
22671                    }
22672                } else {
22673                    mChildren = null;
22674                }
22675            }
22676            mCloseGuard.open("close");
22677        }
22678
22679        @Override
22680        protected void finalize() throws Throwable {
22681            try {
22682                if (mCloseGuard != null) {
22683                    mCloseGuard.warnIfOpen();
22684                }
22685
22686                close();
22687            } finally {
22688                super.finalize();
22689            }
22690        }
22691
22692        @Override
22693        public void close() {
22694            mCloseGuard.close();
22695            if (mClosed.compareAndSet(false, true)) {
22696                synchronized (mPackages) {
22697                    if (mWeFroze) {
22698                        mFrozenPackages.remove(mPackageName);
22699                    }
22700
22701                    if (mChildren != null) {
22702                        for (PackageFreezer freezer : mChildren) {
22703                            freezer.close();
22704                        }
22705                    }
22706                }
22707            }
22708        }
22709    }
22710
22711    /**
22712     * Verify that given package is currently frozen.
22713     */
22714    private void checkPackageFrozen(String packageName) {
22715        synchronized (mPackages) {
22716            if (!mFrozenPackages.contains(packageName)) {
22717                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22718            }
22719        }
22720    }
22721
22722    @Override
22723    public int movePackage(final String packageName, final String volumeUuid) {
22724        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22725
22726        final int callingUid = Binder.getCallingUid();
22727        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22728        final int moveId = mNextMoveId.getAndIncrement();
22729        mHandler.post(new Runnable() {
22730            @Override
22731            public void run() {
22732                try {
22733                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22734                } catch (PackageManagerException e) {
22735                    Slog.w(TAG, "Failed to move " + packageName, e);
22736                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22737                }
22738            }
22739        });
22740        return moveId;
22741    }
22742
22743    private void movePackageInternal(final String packageName, final String volumeUuid,
22744            final int moveId, final int callingUid, UserHandle user)
22745                    throws PackageManagerException {
22746        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22747        final PackageManager pm = mContext.getPackageManager();
22748
22749        final boolean currentAsec;
22750        final String currentVolumeUuid;
22751        final File codeFile;
22752        final String installerPackageName;
22753        final String packageAbiOverride;
22754        final int appId;
22755        final String seinfo;
22756        final String label;
22757        final int targetSdkVersion;
22758        final PackageFreezer freezer;
22759        final int[] installedUserIds;
22760
22761        // reader
22762        synchronized (mPackages) {
22763            final PackageParser.Package pkg = mPackages.get(packageName);
22764            final PackageSetting ps = mSettings.mPackages.get(packageName);
22765            if (pkg == null
22766                    || ps == null
22767                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22768                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22769            }
22770            if (pkg.applicationInfo.isSystemApp()) {
22771                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22772                        "Cannot move system application");
22773            }
22774
22775            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22776            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22777                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22778            if (isInternalStorage && !allow3rdPartyOnInternal) {
22779                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22780                        "3rd party apps are not allowed on internal storage");
22781            }
22782
22783            if (pkg.applicationInfo.isExternalAsec()) {
22784                currentAsec = true;
22785                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22786            } else if (pkg.applicationInfo.isForwardLocked()) {
22787                currentAsec = true;
22788                currentVolumeUuid = "forward_locked";
22789            } else {
22790                currentAsec = false;
22791                currentVolumeUuid = ps.volumeUuid;
22792
22793                final File probe = new File(pkg.codePath);
22794                final File probeOat = new File(probe, "oat");
22795                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22796                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22797                            "Move only supported for modern cluster style installs");
22798                }
22799            }
22800
22801            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22802                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22803                        "Package already moved to " + volumeUuid);
22804            }
22805            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22806                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22807                        "Device admin cannot be moved");
22808            }
22809
22810            if (mFrozenPackages.contains(packageName)) {
22811                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22812                        "Failed to move already frozen package");
22813            }
22814
22815            codeFile = new File(pkg.codePath);
22816            installerPackageName = ps.installerPackageName;
22817            packageAbiOverride = ps.cpuAbiOverrideString;
22818            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22819            seinfo = pkg.applicationInfo.seInfo;
22820            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22821            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22822            freezer = freezePackage(packageName, "movePackageInternal");
22823            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22824        }
22825
22826        final Bundle extras = new Bundle();
22827        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22828        extras.putString(Intent.EXTRA_TITLE, label);
22829        mMoveCallbacks.notifyCreated(moveId, extras);
22830
22831        int installFlags;
22832        final boolean moveCompleteApp;
22833        final File measurePath;
22834
22835        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22836            installFlags = INSTALL_INTERNAL;
22837            moveCompleteApp = !currentAsec;
22838            measurePath = Environment.getDataAppDirectory(volumeUuid);
22839        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22840            installFlags = INSTALL_EXTERNAL;
22841            moveCompleteApp = false;
22842            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22843        } else {
22844            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22845            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22846                    || !volume.isMountedWritable()) {
22847                freezer.close();
22848                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22849                        "Move location not mounted private volume");
22850            }
22851
22852            Preconditions.checkState(!currentAsec);
22853
22854            installFlags = INSTALL_INTERNAL;
22855            moveCompleteApp = true;
22856            measurePath = Environment.getDataAppDirectory(volumeUuid);
22857        }
22858
22859        // If we're moving app data around, we need all the users unlocked
22860        if (moveCompleteApp) {
22861            for (int userId : installedUserIds) {
22862                if (StorageManager.isFileEncryptedNativeOrEmulated()
22863                        && !StorageManager.isUserKeyUnlocked(userId)) {
22864                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22865                            "User " + userId + " must be unlocked");
22866                }
22867            }
22868        }
22869
22870        final PackageStats stats = new PackageStats(null, -1);
22871        synchronized (mInstaller) {
22872            for (int userId : installedUserIds) {
22873                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22874                    freezer.close();
22875                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22876                            "Failed to measure package size");
22877                }
22878            }
22879        }
22880
22881        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22882                + stats.dataSize);
22883
22884        final long startFreeBytes = measurePath.getUsableSpace();
22885        final long sizeBytes;
22886        if (moveCompleteApp) {
22887            sizeBytes = stats.codeSize + stats.dataSize;
22888        } else {
22889            sizeBytes = stats.codeSize;
22890        }
22891
22892        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22893            freezer.close();
22894            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22895                    "Not enough free space to move");
22896        }
22897
22898        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22899
22900        final CountDownLatch installedLatch = new CountDownLatch(1);
22901        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22902            @Override
22903            public void onUserActionRequired(Intent intent) throws RemoteException {
22904                throw new IllegalStateException();
22905            }
22906
22907            @Override
22908            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22909                    Bundle extras) throws RemoteException {
22910                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22911                        + PackageManager.installStatusToString(returnCode, msg));
22912
22913                installedLatch.countDown();
22914                freezer.close();
22915
22916                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22917                switch (status) {
22918                    case PackageInstaller.STATUS_SUCCESS:
22919                        mMoveCallbacks.notifyStatusChanged(moveId,
22920                                PackageManager.MOVE_SUCCEEDED);
22921                        break;
22922                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22923                        mMoveCallbacks.notifyStatusChanged(moveId,
22924                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22925                        break;
22926                    default:
22927                        mMoveCallbacks.notifyStatusChanged(moveId,
22928                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22929                        break;
22930                }
22931            }
22932        };
22933
22934        final MoveInfo move;
22935        if (moveCompleteApp) {
22936            // Kick off a thread to report progress estimates
22937            new Thread() {
22938                @Override
22939                public void run() {
22940                    while (true) {
22941                        try {
22942                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22943                                break;
22944                            }
22945                        } catch (InterruptedException ignored) {
22946                        }
22947
22948                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22949                        final int progress = 10 + (int) MathUtils.constrain(
22950                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22951                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22952                    }
22953                }
22954            }.start();
22955
22956            final String dataAppName = codeFile.getName();
22957            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22958                    dataAppName, appId, seinfo, targetSdkVersion);
22959        } else {
22960            move = null;
22961        }
22962
22963        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22964
22965        final Message msg = mHandler.obtainMessage(INIT_COPY);
22966        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22967        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22968                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22969                packageAbiOverride, null /*grantedPermissions*/,
22970                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22971        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22972        msg.obj = params;
22973
22974        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22975                System.identityHashCode(msg.obj));
22976        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22977                System.identityHashCode(msg.obj));
22978
22979        mHandler.sendMessage(msg);
22980    }
22981
22982    @Override
22983    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22984        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22985
22986        final int realMoveId = mNextMoveId.getAndIncrement();
22987        final Bundle extras = new Bundle();
22988        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22989        mMoveCallbacks.notifyCreated(realMoveId, extras);
22990
22991        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22992            @Override
22993            public void onCreated(int moveId, Bundle extras) {
22994                // Ignored
22995            }
22996
22997            @Override
22998            public void onStatusChanged(int moveId, int status, long estMillis) {
22999                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23000            }
23001        };
23002
23003        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23004        storage.setPrimaryStorageUuid(volumeUuid, callback);
23005        return realMoveId;
23006    }
23007
23008    @Override
23009    public int getMoveStatus(int moveId) {
23010        mContext.enforceCallingOrSelfPermission(
23011                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23012        return mMoveCallbacks.mLastStatus.get(moveId);
23013    }
23014
23015    @Override
23016    public void registerMoveCallback(IPackageMoveObserver callback) {
23017        mContext.enforceCallingOrSelfPermission(
23018                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23019        mMoveCallbacks.register(callback);
23020    }
23021
23022    @Override
23023    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23024        mContext.enforceCallingOrSelfPermission(
23025                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23026        mMoveCallbacks.unregister(callback);
23027    }
23028
23029    @Override
23030    public boolean setInstallLocation(int loc) {
23031        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23032                null);
23033        if (getInstallLocation() == loc) {
23034            return true;
23035        }
23036        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23037                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23038            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23039                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23040            return true;
23041        }
23042        return false;
23043   }
23044
23045    @Override
23046    public int getInstallLocation() {
23047        // allow instant app access
23048        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23049                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23050                PackageHelper.APP_INSTALL_AUTO);
23051    }
23052
23053    /** Called by UserManagerService */
23054    void cleanUpUser(UserManagerService userManager, int userHandle) {
23055        synchronized (mPackages) {
23056            mDirtyUsers.remove(userHandle);
23057            mUserNeedsBadging.delete(userHandle);
23058            mSettings.removeUserLPw(userHandle);
23059            mPendingBroadcasts.remove(userHandle);
23060            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23061            removeUnusedPackagesLPw(userManager, userHandle);
23062        }
23063    }
23064
23065    /**
23066     * We're removing userHandle and would like to remove any downloaded packages
23067     * that are no longer in use by any other user.
23068     * @param userHandle the user being removed
23069     */
23070    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23071        final boolean DEBUG_CLEAN_APKS = false;
23072        int [] users = userManager.getUserIds();
23073        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23074        while (psit.hasNext()) {
23075            PackageSetting ps = psit.next();
23076            if (ps.pkg == null) {
23077                continue;
23078            }
23079            final String packageName = ps.pkg.packageName;
23080            // Skip over if system app
23081            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23082                continue;
23083            }
23084            if (DEBUG_CLEAN_APKS) {
23085                Slog.i(TAG, "Checking package " + packageName);
23086            }
23087            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23088            if (keep) {
23089                if (DEBUG_CLEAN_APKS) {
23090                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23091                }
23092            } else {
23093                for (int i = 0; i < users.length; i++) {
23094                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23095                        keep = true;
23096                        if (DEBUG_CLEAN_APKS) {
23097                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23098                                    + users[i]);
23099                        }
23100                        break;
23101                    }
23102                }
23103            }
23104            if (!keep) {
23105                if (DEBUG_CLEAN_APKS) {
23106                    Slog.i(TAG, "  Removing package " + packageName);
23107                }
23108                mHandler.post(new Runnable() {
23109                    public void run() {
23110                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23111                                userHandle, 0);
23112                    } //end run
23113                });
23114            }
23115        }
23116    }
23117
23118    /** Called by UserManagerService */
23119    void createNewUser(int userId, String[] disallowedPackages) {
23120        synchronized (mInstallLock) {
23121            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23122        }
23123        synchronized (mPackages) {
23124            scheduleWritePackageRestrictionsLocked(userId);
23125            scheduleWritePackageListLocked(userId);
23126            applyFactoryDefaultBrowserLPw(userId);
23127            primeDomainVerificationsLPw(userId);
23128        }
23129    }
23130
23131    void onNewUserCreated(final int userId) {
23132        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23133        synchronized(mPackages) {
23134            // If permission review for legacy apps is required, we represent
23135            // dagerous permissions for such apps as always granted runtime
23136            // permissions to keep per user flag state whether review is needed.
23137            // Hence, if a new user is added we have to propagate dangerous
23138            // permission grants for these legacy apps.
23139            if (mSettings.mPermissions.mPermissionReviewRequired) {
23140// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23141                mPermissionManager.updateAllPermissions(
23142                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23143                        mPermissionCallback);
23144            }
23145        }
23146    }
23147
23148    @Override
23149    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23150        mContext.enforceCallingOrSelfPermission(
23151                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23152                "Only package verification agents can read the verifier device identity");
23153
23154        synchronized (mPackages) {
23155            return mSettings.getVerifierDeviceIdentityLPw();
23156        }
23157    }
23158
23159    @Override
23160    public void setPermissionEnforced(String permission, boolean enforced) {
23161        // TODO: Now that we no longer change GID for storage, this should to away.
23162        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23163                "setPermissionEnforced");
23164        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23165            synchronized (mPackages) {
23166                if (mSettings.mReadExternalStorageEnforced == null
23167                        || mSettings.mReadExternalStorageEnforced != enforced) {
23168                    mSettings.mReadExternalStorageEnforced =
23169                            enforced ? Boolean.TRUE : Boolean.FALSE;
23170                    mSettings.writeLPr();
23171                }
23172            }
23173            // kill any non-foreground processes so we restart them and
23174            // grant/revoke the GID.
23175            final IActivityManager am = ActivityManager.getService();
23176            if (am != null) {
23177                final long token = Binder.clearCallingIdentity();
23178                try {
23179                    am.killProcessesBelowForeground("setPermissionEnforcement");
23180                } catch (RemoteException e) {
23181                } finally {
23182                    Binder.restoreCallingIdentity(token);
23183                }
23184            }
23185        } else {
23186            throw new IllegalArgumentException("No selective enforcement for " + permission);
23187        }
23188    }
23189
23190    @Override
23191    @Deprecated
23192    public boolean isPermissionEnforced(String permission) {
23193        // allow instant applications
23194        return true;
23195    }
23196
23197    @Override
23198    public boolean isStorageLow() {
23199        // allow instant applications
23200        final long token = Binder.clearCallingIdentity();
23201        try {
23202            final DeviceStorageMonitorInternal
23203                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23204            if (dsm != null) {
23205                return dsm.isMemoryLow();
23206            } else {
23207                return false;
23208            }
23209        } finally {
23210            Binder.restoreCallingIdentity(token);
23211        }
23212    }
23213
23214    @Override
23215    public IPackageInstaller getPackageInstaller() {
23216        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23217            return null;
23218        }
23219        return mInstallerService;
23220    }
23221
23222    @Override
23223    public IArtManager getArtManager() {
23224        return mArtManagerService;
23225    }
23226
23227    private boolean userNeedsBadging(int userId) {
23228        int index = mUserNeedsBadging.indexOfKey(userId);
23229        if (index < 0) {
23230            final UserInfo userInfo;
23231            final long token = Binder.clearCallingIdentity();
23232            try {
23233                userInfo = sUserManager.getUserInfo(userId);
23234            } finally {
23235                Binder.restoreCallingIdentity(token);
23236            }
23237            final boolean b;
23238            if (userInfo != null && userInfo.isManagedProfile()) {
23239                b = true;
23240            } else {
23241                b = false;
23242            }
23243            mUserNeedsBadging.put(userId, b);
23244            return b;
23245        }
23246        return mUserNeedsBadging.valueAt(index);
23247    }
23248
23249    @Override
23250    public KeySet getKeySetByAlias(String packageName, String alias) {
23251        if (packageName == null || alias == null) {
23252            return null;
23253        }
23254        synchronized(mPackages) {
23255            final PackageParser.Package pkg = mPackages.get(packageName);
23256            if (pkg == null) {
23257                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23258                throw new IllegalArgumentException("Unknown package: " + packageName);
23259            }
23260            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23261            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23262                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23263                throw new IllegalArgumentException("Unknown package: " + packageName);
23264            }
23265            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23266            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23267        }
23268    }
23269
23270    @Override
23271    public KeySet getSigningKeySet(String packageName) {
23272        if (packageName == null) {
23273            return null;
23274        }
23275        synchronized(mPackages) {
23276            final int callingUid = Binder.getCallingUid();
23277            final int callingUserId = UserHandle.getUserId(callingUid);
23278            final PackageParser.Package pkg = mPackages.get(packageName);
23279            if (pkg == null) {
23280                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23281                throw new IllegalArgumentException("Unknown package: " + packageName);
23282            }
23283            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23284            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23285                // filter and pretend the package doesn't exist
23286                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23287                        + ", uid:" + callingUid);
23288                throw new IllegalArgumentException("Unknown package: " + packageName);
23289            }
23290            if (pkg.applicationInfo.uid != callingUid
23291                    && Process.SYSTEM_UID != callingUid) {
23292                throw new SecurityException("May not access signing KeySet of other apps.");
23293            }
23294            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23295            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23296        }
23297    }
23298
23299    @Override
23300    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23301        final int callingUid = Binder.getCallingUid();
23302        if (getInstantAppPackageName(callingUid) != null) {
23303            return false;
23304        }
23305        if (packageName == null || ks == null) {
23306            return false;
23307        }
23308        synchronized(mPackages) {
23309            final PackageParser.Package pkg = mPackages.get(packageName);
23310            if (pkg == null
23311                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23312                            UserHandle.getUserId(callingUid))) {
23313                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23314                throw new IllegalArgumentException("Unknown package: " + packageName);
23315            }
23316            IBinder ksh = ks.getToken();
23317            if (ksh instanceof KeySetHandle) {
23318                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23319                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23320            }
23321            return false;
23322        }
23323    }
23324
23325    @Override
23326    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23327        final int callingUid = Binder.getCallingUid();
23328        if (getInstantAppPackageName(callingUid) != null) {
23329            return false;
23330        }
23331        if (packageName == null || ks == null) {
23332            return false;
23333        }
23334        synchronized(mPackages) {
23335            final PackageParser.Package pkg = mPackages.get(packageName);
23336            if (pkg == null
23337                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23338                            UserHandle.getUserId(callingUid))) {
23339                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23340                throw new IllegalArgumentException("Unknown package: " + packageName);
23341            }
23342            IBinder ksh = ks.getToken();
23343            if (ksh instanceof KeySetHandle) {
23344                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23345                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23346            }
23347            return false;
23348        }
23349    }
23350
23351    private void deletePackageIfUnusedLPr(final String packageName) {
23352        PackageSetting ps = mSettings.mPackages.get(packageName);
23353        if (ps == null) {
23354            return;
23355        }
23356        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23357            // TODO Implement atomic delete if package is unused
23358            // It is currently possible that the package will be deleted even if it is installed
23359            // after this method returns.
23360            mHandler.post(new Runnable() {
23361                public void run() {
23362                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23363                            0, PackageManager.DELETE_ALL_USERS);
23364                }
23365            });
23366        }
23367    }
23368
23369    /**
23370     * Check and throw if the given before/after packages would be considered a
23371     * downgrade.
23372     */
23373    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23374            throws PackageManagerException {
23375        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23376            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23377                    "Update version code " + after.versionCode + " is older than current "
23378                    + before.getLongVersionCode());
23379        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23380            if (after.baseRevisionCode < before.baseRevisionCode) {
23381                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23382                        "Update base revision code " + after.baseRevisionCode
23383                        + " is older than current " + before.baseRevisionCode);
23384            }
23385
23386            if (!ArrayUtils.isEmpty(after.splitNames)) {
23387                for (int i = 0; i < after.splitNames.length; i++) {
23388                    final String splitName = after.splitNames[i];
23389                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23390                    if (j != -1) {
23391                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23392                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23393                                    "Update split " + splitName + " revision code "
23394                                    + after.splitRevisionCodes[i] + " is older than current "
23395                                    + before.splitRevisionCodes[j]);
23396                        }
23397                    }
23398                }
23399            }
23400        }
23401    }
23402
23403    private static class MoveCallbacks extends Handler {
23404        private static final int MSG_CREATED = 1;
23405        private static final int MSG_STATUS_CHANGED = 2;
23406
23407        private final RemoteCallbackList<IPackageMoveObserver>
23408                mCallbacks = new RemoteCallbackList<>();
23409
23410        private final SparseIntArray mLastStatus = new SparseIntArray();
23411
23412        public MoveCallbacks(Looper looper) {
23413            super(looper);
23414        }
23415
23416        public void register(IPackageMoveObserver callback) {
23417            mCallbacks.register(callback);
23418        }
23419
23420        public void unregister(IPackageMoveObserver callback) {
23421            mCallbacks.unregister(callback);
23422        }
23423
23424        @Override
23425        public void handleMessage(Message msg) {
23426            final SomeArgs args = (SomeArgs) msg.obj;
23427            final int n = mCallbacks.beginBroadcast();
23428            for (int i = 0; i < n; i++) {
23429                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23430                try {
23431                    invokeCallback(callback, msg.what, args);
23432                } catch (RemoteException ignored) {
23433                }
23434            }
23435            mCallbacks.finishBroadcast();
23436            args.recycle();
23437        }
23438
23439        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23440                throws RemoteException {
23441            switch (what) {
23442                case MSG_CREATED: {
23443                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23444                    break;
23445                }
23446                case MSG_STATUS_CHANGED: {
23447                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23448                    break;
23449                }
23450            }
23451        }
23452
23453        private void notifyCreated(int moveId, Bundle extras) {
23454            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23455
23456            final SomeArgs args = SomeArgs.obtain();
23457            args.argi1 = moveId;
23458            args.arg2 = extras;
23459            obtainMessage(MSG_CREATED, args).sendToTarget();
23460        }
23461
23462        private void notifyStatusChanged(int moveId, int status) {
23463            notifyStatusChanged(moveId, status, -1);
23464        }
23465
23466        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23467            Slog.v(TAG, "Move " + moveId + " status " + status);
23468
23469            final SomeArgs args = SomeArgs.obtain();
23470            args.argi1 = moveId;
23471            args.argi2 = status;
23472            args.arg3 = estMillis;
23473            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23474
23475            synchronized (mLastStatus) {
23476                mLastStatus.put(moveId, status);
23477            }
23478        }
23479    }
23480
23481    private final static class OnPermissionChangeListeners extends Handler {
23482        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23483
23484        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23485                new RemoteCallbackList<>();
23486
23487        public OnPermissionChangeListeners(Looper looper) {
23488            super(looper);
23489        }
23490
23491        @Override
23492        public void handleMessage(Message msg) {
23493            switch (msg.what) {
23494                case MSG_ON_PERMISSIONS_CHANGED: {
23495                    final int uid = msg.arg1;
23496                    handleOnPermissionsChanged(uid);
23497                } break;
23498            }
23499        }
23500
23501        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23502            mPermissionListeners.register(listener);
23503
23504        }
23505
23506        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23507            mPermissionListeners.unregister(listener);
23508        }
23509
23510        public void onPermissionsChanged(int uid) {
23511            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23512                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23513            }
23514        }
23515
23516        private void handleOnPermissionsChanged(int uid) {
23517            final int count = mPermissionListeners.beginBroadcast();
23518            try {
23519                for (int i = 0; i < count; i++) {
23520                    IOnPermissionsChangeListener callback = mPermissionListeners
23521                            .getBroadcastItem(i);
23522                    try {
23523                        callback.onPermissionsChanged(uid);
23524                    } catch (RemoteException e) {
23525                        Log.e(TAG, "Permission listener is dead", e);
23526                    }
23527                }
23528            } finally {
23529                mPermissionListeners.finishBroadcast();
23530            }
23531        }
23532    }
23533
23534    private class PackageManagerNative extends IPackageManagerNative.Stub {
23535        @Override
23536        public String[] getNamesForUids(int[] uids) throws RemoteException {
23537            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23538            // massage results so they can be parsed by the native binder
23539            for (int i = results.length - 1; i >= 0; --i) {
23540                if (results[i] == null) {
23541                    results[i] = "";
23542                }
23543            }
23544            return results;
23545        }
23546
23547        // NB: this differentiates between preloads and sideloads
23548        @Override
23549        public String getInstallerForPackage(String packageName) throws RemoteException {
23550            final String installerName = getInstallerPackageName(packageName);
23551            if (!TextUtils.isEmpty(installerName)) {
23552                return installerName;
23553            }
23554            // differentiate between preload and sideload
23555            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23556            ApplicationInfo appInfo = getApplicationInfo(packageName,
23557                                    /*flags*/ 0,
23558                                    /*userId*/ callingUser);
23559            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23560                return "preload";
23561            }
23562            return "";
23563        }
23564
23565        @Override
23566        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23567            try {
23568                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23569                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23570                if (pInfo != null) {
23571                    return pInfo.getLongVersionCode();
23572                }
23573            } catch (Exception e) {
23574            }
23575            return 0;
23576        }
23577    }
23578
23579    private class PackageManagerInternalImpl extends PackageManagerInternal {
23580        @Override
23581        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23582                int flagValues, int userId) {
23583            PackageManagerService.this.updatePermissionFlags(
23584                    permName, packageName, flagMask, flagValues, userId);
23585        }
23586
23587        @Override
23588        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23589            SigningDetails sd = getSigningDetails(packageName);
23590            if (sd == null) {
23591                return false;
23592            }
23593            return sd.hasSha256Certificate(restoringFromSigHash,
23594                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23595        }
23596
23597        @Override
23598        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23599            SigningDetails sd = getSigningDetails(packageName);
23600            if (sd == null) {
23601                return false;
23602            }
23603            return sd.hasCertificate(restoringFromSig,
23604                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23605        }
23606
23607        @Override
23608        public boolean hasSignatureCapability(int serverUid, int clientUid,
23609                @SigningDetails.CertCapabilities int capability) {
23610            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23611            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23612            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23613                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23614
23615        }
23616
23617        private SigningDetails getSigningDetails(@NonNull String packageName) {
23618            synchronized (mPackages) {
23619                PackageParser.Package p = mPackages.get(packageName);
23620                if (p == null) {
23621                    return null;
23622                }
23623                return p.mSigningDetails;
23624            }
23625        }
23626
23627        private SigningDetails getSigningDetails(int uid) {
23628            synchronized (mPackages) {
23629                final int appId = UserHandle.getAppId(uid);
23630                final Object obj = mSettings.getUserIdLPr(appId);
23631                if (obj != null) {
23632                    if (obj instanceof SharedUserSetting) {
23633                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23634                    } else if (obj instanceof PackageSetting) {
23635                        final PackageSetting ps = (PackageSetting) obj;
23636                        return ps.signatures.mSigningDetails;
23637                    }
23638                }
23639                return SigningDetails.UNKNOWN;
23640            }
23641        }
23642
23643        @Override
23644        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23645            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23646        }
23647
23648        @Override
23649        public boolean isInstantApp(String packageName, int userId) {
23650            return PackageManagerService.this.isInstantApp(packageName, userId);
23651        }
23652
23653        @Override
23654        public String getInstantAppPackageName(int uid) {
23655            return PackageManagerService.this.getInstantAppPackageName(uid);
23656        }
23657
23658        @Override
23659        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23660            synchronized (mPackages) {
23661                return PackageManagerService.this.filterAppAccessLPr(
23662                        (PackageSetting) pkg.mExtras, callingUid, userId);
23663            }
23664        }
23665
23666        @Override
23667        public PackageParser.Package getPackage(String packageName) {
23668            synchronized (mPackages) {
23669                packageName = resolveInternalPackageNameLPr(
23670                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23671                return mPackages.get(packageName);
23672            }
23673        }
23674
23675        @Override
23676        public PackageList getPackageList(PackageListObserver observer) {
23677            synchronized (mPackages) {
23678                final int N = mPackages.size();
23679                final ArrayList<String> list = new ArrayList<>(N);
23680                for (int i = 0; i < N; i++) {
23681                    list.add(mPackages.keyAt(i));
23682                }
23683                final PackageList packageList = new PackageList(list, observer);
23684                if (observer != null) {
23685                    mPackageListObservers.add(packageList);
23686                }
23687                return packageList;
23688            }
23689        }
23690
23691        @Override
23692        public void removePackageListObserver(PackageListObserver observer) {
23693            synchronized (mPackages) {
23694                mPackageListObservers.remove(observer);
23695            }
23696        }
23697
23698        @Override
23699        public PackageParser.Package getDisabledPackage(String packageName) {
23700            synchronized (mPackages) {
23701                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23702                return (ps != null) ? ps.pkg : null;
23703            }
23704        }
23705
23706        @Override
23707        public String getKnownPackageName(int knownPackage, int userId) {
23708            switch(knownPackage) {
23709                case PackageManagerInternal.PACKAGE_BROWSER:
23710                    return getDefaultBrowserPackageName(userId);
23711                case PackageManagerInternal.PACKAGE_INSTALLER:
23712                    return mRequiredInstallerPackage;
23713                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23714                    return mSetupWizardPackage;
23715                case PackageManagerInternal.PACKAGE_SYSTEM:
23716                    return "android";
23717                case PackageManagerInternal.PACKAGE_VERIFIER:
23718                    return mRequiredVerifierPackage;
23719                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23720                    return mSystemTextClassifierPackage;
23721            }
23722            return null;
23723        }
23724
23725        @Override
23726        public boolean isResolveActivityComponent(ComponentInfo component) {
23727            return mResolveActivity.packageName.equals(component.packageName)
23728                    && mResolveActivity.name.equals(component.name);
23729        }
23730
23731        @Override
23732        public void setLocationPackagesProvider(PackagesProvider provider) {
23733            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23734        }
23735
23736        @Override
23737        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23738            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23739        }
23740
23741        @Override
23742        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23743            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23744        }
23745
23746        @Override
23747        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23748            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23749        }
23750
23751        @Override
23752        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23753            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23754        }
23755
23756        @Override
23757        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23758            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23759        }
23760
23761        @Override
23762        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23763            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23764        }
23765
23766        @Override
23767        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23768            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23769        }
23770
23771        @Override
23772        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23773            synchronized (mPackages) {
23774                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23775            }
23776            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23777        }
23778
23779        @Override
23780        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23781            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23782                    packageName, userId);
23783        }
23784
23785        @Override
23786        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23787            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23788                    packageName, userId);
23789        }
23790
23791        @Override
23792        public void setKeepUninstalledPackages(final List<String> packageList) {
23793            Preconditions.checkNotNull(packageList);
23794            List<String> removedFromList = null;
23795            synchronized (mPackages) {
23796                if (mKeepUninstalledPackages != null) {
23797                    final int packagesCount = mKeepUninstalledPackages.size();
23798                    for (int i = 0; i < packagesCount; i++) {
23799                        String oldPackage = mKeepUninstalledPackages.get(i);
23800                        if (packageList != null && packageList.contains(oldPackage)) {
23801                            continue;
23802                        }
23803                        if (removedFromList == null) {
23804                            removedFromList = new ArrayList<>();
23805                        }
23806                        removedFromList.add(oldPackage);
23807                    }
23808                }
23809                mKeepUninstalledPackages = new ArrayList<>(packageList);
23810                if (removedFromList != null) {
23811                    final int removedCount = removedFromList.size();
23812                    for (int i = 0; i < removedCount; i++) {
23813                        deletePackageIfUnusedLPr(removedFromList.get(i));
23814                    }
23815                }
23816            }
23817        }
23818
23819        @Override
23820        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23821            synchronized (mPackages) {
23822                return mPermissionManager.isPermissionsReviewRequired(
23823                        mPackages.get(packageName), userId);
23824            }
23825        }
23826
23827        @Override
23828        public PackageInfo getPackageInfo(
23829                String packageName, int flags, int filterCallingUid, int userId) {
23830            return PackageManagerService.this
23831                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23832                            flags, filterCallingUid, userId);
23833        }
23834
23835        @Override
23836        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23837            synchronized (mPackages) {
23838                final PackageSetting ps = mSettings.mPackages.get(packageName);
23839                PersistableBundle launcherExtras = null;
23840                if (ps != null) {
23841                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23842                }
23843                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23844            }
23845        }
23846
23847        @Override
23848        public boolean isPackageSuspended(String packageName, int userId) {
23849            synchronized (mPackages) {
23850                final PackageSetting ps = mSettings.mPackages.get(packageName);
23851                return (ps != null) ? ps.getSuspended(userId) : false;
23852            }
23853        }
23854
23855        @Override
23856        public String getSuspendingPackage(String suspendedPackage, int userId) {
23857            synchronized (mPackages) {
23858                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23859                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23860            }
23861        }
23862
23863        @Override
23864        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23865            synchronized (mPackages) {
23866                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23867                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23868            }
23869        }
23870
23871        @Override
23872        public int getPackageUid(String packageName, int flags, int userId) {
23873            return PackageManagerService.this
23874                    .getPackageUid(packageName, flags, userId);
23875        }
23876
23877        @Override
23878        public ApplicationInfo getApplicationInfo(
23879                String packageName, int flags, int filterCallingUid, int userId) {
23880            return PackageManagerService.this
23881                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23882        }
23883
23884        @Override
23885        public ActivityInfo getActivityInfo(
23886                ComponentName component, int flags, int filterCallingUid, int userId) {
23887            return PackageManagerService.this
23888                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23889        }
23890
23891        @Override
23892        public List<ResolveInfo> queryIntentActivities(
23893                Intent intent, int flags, int filterCallingUid, int userId) {
23894            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23895            return PackageManagerService.this
23896                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23897                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23898        }
23899
23900        @Override
23901        public List<ResolveInfo> queryIntentServices(
23902                Intent intent, int flags, int callingUid, int userId) {
23903            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23904            return PackageManagerService.this
23905                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23906                            false);
23907        }
23908
23909        @Override
23910        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23911                int userId) {
23912            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23913        }
23914
23915        @Override
23916        public ComponentName getDefaultHomeActivity(int userId) {
23917            return PackageManagerService.this.getDefaultHomeActivity(userId);
23918        }
23919
23920        @Override
23921        public void setDeviceAndProfileOwnerPackages(
23922                int deviceOwnerUserId, String deviceOwnerPackage,
23923                SparseArray<String> profileOwnerPackages) {
23924            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23925                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23926        }
23927
23928        @Override
23929        public boolean isPackageDataProtected(int userId, String packageName) {
23930            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23931        }
23932
23933        @Override
23934        public boolean isPackageStateProtected(String packageName, int userId) {
23935            return mProtectedPackages.isPackageStateProtected(userId, packageName);
23936        }
23937
23938        @Override
23939        public boolean isPackageEphemeral(int userId, String packageName) {
23940            synchronized (mPackages) {
23941                final PackageSetting ps = mSettings.mPackages.get(packageName);
23942                return ps != null ? ps.getInstantApp(userId) : false;
23943            }
23944        }
23945
23946        @Override
23947        public boolean wasPackageEverLaunched(String packageName, int userId) {
23948            synchronized (mPackages) {
23949                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23950            }
23951        }
23952
23953        @Override
23954        public void grantRuntimePermission(String packageName, String permName, int userId,
23955                boolean overridePolicy) {
23956            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23957                    permName, packageName, overridePolicy, getCallingUid(), userId,
23958                    mPermissionCallback);
23959        }
23960
23961        @Override
23962        public void revokeRuntimePermission(String packageName, String permName, int userId,
23963                boolean overridePolicy) {
23964            mPermissionManager.revokeRuntimePermission(
23965                    permName, packageName, overridePolicy, getCallingUid(), userId,
23966                    mPermissionCallback);
23967        }
23968
23969        @Override
23970        public String getNameForUid(int uid) {
23971            return PackageManagerService.this.getNameForUid(uid);
23972        }
23973
23974        @Override
23975        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23976                Intent origIntent, String resolvedType, String callingPackage,
23977                Bundle verificationBundle, int userId) {
23978            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23979                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23980                    userId);
23981        }
23982
23983        @Override
23984        public void grantEphemeralAccess(int userId, Intent intent,
23985                int targetAppId, int ephemeralAppId) {
23986            synchronized (mPackages) {
23987                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23988                        targetAppId, ephemeralAppId);
23989            }
23990        }
23991
23992        @Override
23993        public boolean isInstantAppInstallerComponent(ComponentName component) {
23994            synchronized (mPackages) {
23995                return mInstantAppInstallerActivity != null
23996                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23997            }
23998        }
23999
24000        @Override
24001        public void pruneInstantApps() {
24002            mInstantAppRegistry.pruneInstantApps();
24003        }
24004
24005        @Override
24006        public String getSetupWizardPackageName() {
24007            return mSetupWizardPackage;
24008        }
24009
24010        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24011            if (policy != null) {
24012                mExternalSourcesPolicy = policy;
24013            }
24014        }
24015
24016        @Override
24017        public boolean isPackagePersistent(String packageName) {
24018            synchronized (mPackages) {
24019                PackageParser.Package pkg = mPackages.get(packageName);
24020                return pkg != null
24021                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24022                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24023                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24024                        : false;
24025            }
24026        }
24027
24028        @Override
24029        public boolean isLegacySystemApp(Package pkg) {
24030            synchronized (mPackages) {
24031                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24032                return mPromoteSystemApps
24033                        && ps.isSystem()
24034                        && mExistingSystemPackages.contains(ps.name);
24035            }
24036        }
24037
24038        @Override
24039        public List<PackageInfo> getOverlayPackages(int userId) {
24040            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24041            synchronized (mPackages) {
24042                for (PackageParser.Package p : mPackages.values()) {
24043                    if (p.mOverlayTarget != null) {
24044                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24045                        if (pkg != null) {
24046                            overlayPackages.add(pkg);
24047                        }
24048                    }
24049                }
24050            }
24051            return overlayPackages;
24052        }
24053
24054        @Override
24055        public List<String> getTargetPackageNames(int userId) {
24056            List<String> targetPackages = new ArrayList<>();
24057            synchronized (mPackages) {
24058                for (PackageParser.Package p : mPackages.values()) {
24059                    if (p.mOverlayTarget == null) {
24060                        targetPackages.add(p.packageName);
24061                    }
24062                }
24063            }
24064            return targetPackages;
24065        }
24066
24067        @Override
24068        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24069                @Nullable List<String> overlayPackageNames) {
24070            synchronized (mPackages) {
24071                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24072                    Slog.e(TAG, "failed to find package " + targetPackageName);
24073                    return false;
24074                }
24075                ArrayList<String> overlayPaths = null;
24076                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24077                    final int N = overlayPackageNames.size();
24078                    overlayPaths = new ArrayList<>(N);
24079                    for (int i = 0; i < N; i++) {
24080                        final String packageName = overlayPackageNames.get(i);
24081                        final PackageParser.Package pkg = mPackages.get(packageName);
24082                        if (pkg == null) {
24083                            Slog.e(TAG, "failed to find package " + packageName);
24084                            return false;
24085                        }
24086                        overlayPaths.add(pkg.baseCodePath);
24087                    }
24088                }
24089
24090                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24091                ps.setOverlayPaths(overlayPaths, userId);
24092                return true;
24093            }
24094        }
24095
24096        @Override
24097        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24098                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24099            return resolveIntentInternal(
24100                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24101        }
24102
24103        @Override
24104        public ResolveInfo resolveService(Intent intent, String resolvedType,
24105                int flags, int userId, int callingUid) {
24106            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24107        }
24108
24109        @Override
24110        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24111            return PackageManagerService.this.resolveContentProviderInternal(
24112                    name, flags, userId);
24113        }
24114
24115        @Override
24116        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24117            synchronized (mPackages) {
24118                mIsolatedOwners.put(isolatedUid, ownerUid);
24119            }
24120        }
24121
24122        @Override
24123        public void removeIsolatedUid(int isolatedUid) {
24124            synchronized (mPackages) {
24125                mIsolatedOwners.delete(isolatedUid);
24126            }
24127        }
24128
24129        @Override
24130        public int getUidTargetSdkVersion(int uid) {
24131            synchronized (mPackages) {
24132                return getUidTargetSdkVersionLockedLPr(uid);
24133            }
24134        }
24135
24136        @Override
24137        public int getPackageTargetSdkVersion(String packageName) {
24138            synchronized (mPackages) {
24139                return getPackageTargetSdkVersionLockedLPr(packageName);
24140            }
24141        }
24142
24143        @Override
24144        public boolean canAccessInstantApps(int callingUid, int userId) {
24145            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24146        }
24147
24148        @Override
24149        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24150            synchronized (mPackages) {
24151                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24152                return !PackageManagerService.this.filterAppAccessLPr(
24153                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24154            }
24155        }
24156
24157        @Override
24158        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24159            synchronized (mPackages) {
24160                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24161            }
24162        }
24163
24164        @Override
24165        public void notifyPackageUse(String packageName, int reason) {
24166            synchronized (mPackages) {
24167                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24168            }
24169        }
24170    }
24171
24172    @Override
24173    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24174        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24175        synchronized (mPackages) {
24176            final long identity = Binder.clearCallingIdentity();
24177            try {
24178                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24179                        packageNames, userId);
24180            } finally {
24181                Binder.restoreCallingIdentity(identity);
24182            }
24183        }
24184    }
24185
24186    @Override
24187    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24188        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24189        synchronized (mPackages) {
24190            final long identity = Binder.clearCallingIdentity();
24191            try {
24192                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24193                        packageNames, userId);
24194            } finally {
24195                Binder.restoreCallingIdentity(identity);
24196            }
24197        }
24198    }
24199
24200    @Override
24201    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24202            String[] packageNames, int userId) {
24203        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24204        synchronized (mPackages) {
24205            Binder.withCleanCallingIdentity( () -> {
24206                mDefaultPermissionPolicy.
24207                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24208                                packageNames, userId);
24209            });
24210        }
24211    }
24212
24213    @Override
24214    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24215            String[] packageNames, int userId) {
24216        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24217        synchronized (mPackages) {
24218            Binder.withCleanCallingIdentity( () -> {
24219                mDefaultPermissionPolicy.
24220                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24221                                packageNames, userId);
24222            });
24223        }
24224    }
24225
24226    @Override
24227    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24228        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24229        synchronized (mPackages) {
24230            final long identity = Binder.clearCallingIdentity();
24231            try {
24232                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24233                        packageName, userId);
24234            } finally {
24235                Binder.restoreCallingIdentity(identity);
24236            }
24237        }
24238    }
24239
24240    @Override
24241    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24242        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24243        synchronized (mPackages) {
24244            final long identity = Binder.clearCallingIdentity();
24245            try {
24246                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24247            } finally {
24248                Binder.restoreCallingIdentity(identity);
24249            }
24250        }
24251    }
24252
24253    private static void enforceSystemOrPhoneCaller(String tag) {
24254        int callingUid = Binder.getCallingUid();
24255        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24256            throw new SecurityException(
24257                    "Cannot call " + tag + " from UID " + callingUid);
24258        }
24259    }
24260
24261    boolean isHistoricalPackageUsageAvailable() {
24262        return mPackageUsage.isHistoricalPackageUsageAvailable();
24263    }
24264
24265    /**
24266     * Return a <b>copy</b> of the collection of packages known to the package manager.
24267     * @return A copy of the values of mPackages.
24268     */
24269    Collection<PackageParser.Package> getPackages() {
24270        synchronized (mPackages) {
24271            return new ArrayList<>(mPackages.values());
24272        }
24273    }
24274
24275    /**
24276     * Logs process start information (including base APK hash) to the security log.
24277     * @hide
24278     */
24279    @Override
24280    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24281            String apkFile, int pid) {
24282        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24283            return;
24284        }
24285        if (!SecurityLog.isLoggingEnabled()) {
24286            return;
24287        }
24288        Bundle data = new Bundle();
24289        data.putLong("startTimestamp", System.currentTimeMillis());
24290        data.putString("processName", processName);
24291        data.putInt("uid", uid);
24292        data.putString("seinfo", seinfo);
24293        data.putString("apkFile", apkFile);
24294        data.putInt("pid", pid);
24295        Message msg = mProcessLoggingHandler.obtainMessage(
24296                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24297        msg.setData(data);
24298        mProcessLoggingHandler.sendMessage(msg);
24299    }
24300
24301    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24302        return mCompilerStats.getPackageStats(pkgName);
24303    }
24304
24305    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24306        return getOrCreateCompilerPackageStats(pkg.packageName);
24307    }
24308
24309    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24310        return mCompilerStats.getOrCreatePackageStats(pkgName);
24311    }
24312
24313    public void deleteCompilerPackageStats(String pkgName) {
24314        mCompilerStats.deletePackageStats(pkgName);
24315    }
24316
24317    @Override
24318    public int getInstallReason(String packageName, int userId) {
24319        final int callingUid = Binder.getCallingUid();
24320        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24321                true /* requireFullPermission */, false /* checkShell */,
24322                "get install reason");
24323        synchronized (mPackages) {
24324            final PackageSetting ps = mSettings.mPackages.get(packageName);
24325            if (filterAppAccessLPr(ps, callingUid, userId)) {
24326                return PackageManager.INSTALL_REASON_UNKNOWN;
24327            }
24328            if (ps != null) {
24329                return ps.getInstallReason(userId);
24330            }
24331        }
24332        return PackageManager.INSTALL_REASON_UNKNOWN;
24333    }
24334
24335    @Override
24336    public boolean canRequestPackageInstalls(String packageName, int userId) {
24337        return canRequestPackageInstallsInternal(packageName, 0, userId,
24338                true /* throwIfPermNotDeclared*/);
24339    }
24340
24341    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24342            boolean throwIfPermNotDeclared) {
24343        int callingUid = Binder.getCallingUid();
24344        int uid = getPackageUid(packageName, 0, userId);
24345        if (callingUid != uid && callingUid != Process.ROOT_UID
24346                && callingUid != Process.SYSTEM_UID) {
24347            throw new SecurityException(
24348                    "Caller uid " + callingUid + " does not own package " + packageName);
24349        }
24350        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24351        if (info == null) {
24352            return false;
24353        }
24354        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24355            return false;
24356        }
24357        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24358        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24359        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24360            if (throwIfPermNotDeclared) {
24361                throw new SecurityException("Need to declare " + appOpPermission
24362                        + " to call this api");
24363            } else {
24364                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24365                return false;
24366            }
24367        }
24368        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24369            return false;
24370        }
24371        if (mExternalSourcesPolicy != null) {
24372            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24373            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24374                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24375            }
24376        }
24377        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24378    }
24379
24380    @Override
24381    public ComponentName getInstantAppResolverSettingsComponent() {
24382        return mInstantAppResolverSettingsComponent;
24383    }
24384
24385    @Override
24386    public ComponentName getInstantAppInstallerComponent() {
24387        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24388            return null;
24389        }
24390        return mInstantAppInstallerActivity == null
24391                ? null : mInstantAppInstallerActivity.getComponentName();
24392    }
24393
24394    @Override
24395    public String getInstantAppAndroidId(String packageName, int userId) {
24396        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24397                "getInstantAppAndroidId");
24398        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24399                true /* requireFullPermission */, false /* checkShell */,
24400                "getInstantAppAndroidId");
24401        // Make sure the target is an Instant App.
24402        if (!isInstantApp(packageName, userId)) {
24403            return null;
24404        }
24405        synchronized (mPackages) {
24406            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24407        }
24408    }
24409
24410    boolean canHaveOatDir(String packageName) {
24411        synchronized (mPackages) {
24412            PackageParser.Package p = mPackages.get(packageName);
24413            if (p == null) {
24414                return false;
24415            }
24416            return p.canHaveOatDir();
24417        }
24418    }
24419
24420    private String getOatDir(PackageParser.Package pkg) {
24421        if (!pkg.canHaveOatDir()) {
24422            return null;
24423        }
24424        File codePath = new File(pkg.codePath);
24425        if (codePath.isDirectory()) {
24426            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24427        }
24428        return null;
24429    }
24430
24431    void deleteOatArtifactsOfPackage(String packageName) {
24432        final String[] instructionSets;
24433        final List<String> codePaths;
24434        final String oatDir;
24435        final PackageParser.Package pkg;
24436        synchronized (mPackages) {
24437            pkg = mPackages.get(packageName);
24438        }
24439        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24440        codePaths = pkg.getAllCodePaths();
24441        oatDir = getOatDir(pkg);
24442
24443        for (String codePath : codePaths) {
24444            for (String isa : instructionSets) {
24445                try {
24446                    mInstaller.deleteOdex(codePath, isa, oatDir);
24447                } catch (InstallerException e) {
24448                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24449                }
24450            }
24451        }
24452    }
24453
24454    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24455        Set<String> unusedPackages = new HashSet<>();
24456        long currentTimeInMillis = System.currentTimeMillis();
24457        synchronized (mPackages) {
24458            for (PackageParser.Package pkg : mPackages.values()) {
24459                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24460                if (ps == null) {
24461                    continue;
24462                }
24463                PackageDexUsage.PackageUseInfo packageUseInfo =
24464                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24465                if (PackageManagerServiceUtils
24466                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24467                                downgradeTimeThresholdMillis, packageUseInfo,
24468                                pkg.getLatestPackageUseTimeInMills(),
24469                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24470                    unusedPackages.add(pkg.packageName);
24471                }
24472            }
24473        }
24474        return unusedPackages;
24475    }
24476
24477    @Override
24478    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24479            int userId) {
24480        final int callingUid = Binder.getCallingUid();
24481        final int callingAppId = UserHandle.getAppId(callingUid);
24482
24483        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24484                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24485
24486        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24487                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24488            throw new SecurityException("Caller must have the "
24489                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24490        }
24491
24492        synchronized(mPackages) {
24493            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24494            scheduleWritePackageRestrictionsLocked(userId);
24495        }
24496    }
24497
24498    @Nullable
24499    @Override
24500    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24501        final int callingUid = Binder.getCallingUid();
24502        final int callingAppId = UserHandle.getAppId(callingUid);
24503
24504        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24505                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24506
24507        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24508                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24509            throw new SecurityException("Caller must have the "
24510                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24511        }
24512
24513        synchronized(mPackages) {
24514            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24515        }
24516    }
24517
24518    @Override
24519    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24520        final int callingUid = Binder.getCallingUid();
24521        final int callingAppId = UserHandle.getAppId(callingUid);
24522
24523        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24524                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24525
24526        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24527                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24528            throw new SecurityException("Caller must have the "
24529                    + MANAGE_DEVICE_ADMINS + " permission.");
24530        }
24531
24532        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24533    }
24534}
24535
24536interface PackageSender {
24537    /**
24538     * @param userIds User IDs where the action occurred on a full application
24539     * @param instantUserIds User IDs where the action occurred on an instant application
24540     */
24541    void sendPackageBroadcast(final String action, final String pkg,
24542        final Bundle extras, final int flags, final String targetPkg,
24543        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24544    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24545        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24546    void notifyPackageAdded(String packageName);
24547    void notifyPackageRemoved(String packageName);
24548}
24549