PackageManagerService.java revision 7ea5378f8962a58adfb3702bcd9625aec78b3c7d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendElement;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.SELinuxUtil;
190import android.content.pm.ServiceInfo;
191import android.content.pm.SharedLibraryInfo;
192import android.content.pm.Signature;
193import android.content.pm.UserInfo;
194import android.content.pm.VerifierDeviceIdentity;
195import android.content.pm.VerifierInfo;
196import android.content.pm.VersionedPackage;
197import android.content.pm.dex.ArtManager;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.AsyncTask;
206import android.os.Binder;
207import android.os.Build;
208import android.os.Bundle;
209import android.os.Debug;
210import android.os.Environment;
211import android.os.Environment.UserEnvironment;
212import android.os.FileUtils;
213import android.os.Handler;
214import android.os.IBinder;
215import android.os.Looper;
216import android.os.Message;
217import android.os.Parcel;
218import android.os.ParcelFileDescriptor;
219import android.os.PatternMatcher;
220import android.os.PersistableBundle;
221import android.os.Process;
222import android.os.RemoteCallbackList;
223import android.os.RemoteException;
224import android.os.ResultReceiver;
225import android.os.SELinux;
226import android.os.ServiceManager;
227import android.os.ShellCallback;
228import android.os.SystemClock;
229import android.os.SystemProperties;
230import android.os.Trace;
231import android.os.UserHandle;
232import android.os.UserManager;
233import android.os.UserManagerInternal;
234import android.os.storage.IStorageManager;
235import android.os.storage.StorageEventListener;
236import android.os.storage.StorageManager;
237import android.os.storage.StorageManagerInternal;
238import android.os.storage.VolumeInfo;
239import android.os.storage.VolumeRecord;
240import android.provider.Settings.Global;
241import android.provider.Settings.Secure;
242import android.security.KeyStore;
243import android.security.SystemKeyStore;
244import android.service.pm.PackageServiceDumpProto;
245import android.system.ErrnoException;
246import android.system.Os;
247import android.text.TextUtils;
248import android.text.format.DateUtils;
249import android.util.ArrayMap;
250import android.util.ArraySet;
251import android.util.Base64;
252import android.util.ByteStringUtils;
253import android.util.DisplayMetrics;
254import android.util.EventLog;
255import android.util.ExceptionUtils;
256import android.util.Log;
257import android.util.LogPrinter;
258import android.util.LongSparseArray;
259import android.util.LongSparseLongArray;
260import android.util.MathUtils;
261import android.util.PackageUtils;
262import android.util.Pair;
263import android.util.PrintStreamPrinter;
264import android.util.Slog;
265import android.util.SparseArray;
266import android.util.SparseBooleanArray;
267import android.util.SparseIntArray;
268import android.util.TimingsTraceLog;
269import android.util.Xml;
270import android.util.jar.StrictJarFile;
271import android.util.proto.ProtoOutputStream;
272import android.view.Display;
273
274import com.android.internal.R;
275import com.android.internal.annotations.GuardedBy;
276import com.android.internal.app.IMediaContainerService;
277import com.android.internal.app.ResolverActivity;
278import com.android.internal.app.SuspendedAppActivity;
279import com.android.internal.content.NativeLibraryHelper;
280import com.android.internal.content.PackageHelper;
281import com.android.internal.logging.MetricsLogger;
282import com.android.internal.os.IParcelFileDescriptorFactory;
283import com.android.internal.os.SomeArgs;
284import com.android.internal.os.Zygote;
285import com.android.internal.telephony.CarrierAppUtils;
286import com.android.internal.util.ArrayUtils;
287import com.android.internal.util.ConcurrentUtils;
288import com.android.internal.util.DumpUtils;
289import com.android.internal.util.FastXmlSerializer;
290import com.android.internal.util.IndentingPrintWriter;
291import com.android.internal.util.Preconditions;
292import com.android.internal.util.XmlUtils;
293import com.android.server.AttributeCache;
294import com.android.server.DeviceIdleController;
295import com.android.server.EventLogTags;
296import com.android.server.FgThread;
297import com.android.server.IntentResolver;
298import com.android.server.LocalServices;
299import com.android.server.LockGuard;
300import com.android.server.ServiceThread;
301import com.android.server.SystemConfig;
302import com.android.server.SystemServerInitThreadPool;
303import com.android.server.Watchdog;
304import com.android.server.net.NetworkPolicyManagerInternal;
305import com.android.server.pm.Installer.InstallerException;
306import com.android.server.pm.Settings.DatabaseVersion;
307import com.android.server.pm.Settings.VersionInfo;
308import com.android.server.pm.dex.ArtManagerService;
309import com.android.server.pm.dex.DexLogger;
310import com.android.server.pm.dex.DexManager;
311import com.android.server.pm.dex.DexoptOptions;
312import com.android.server.pm.dex.PackageDexUsage;
313import com.android.server.pm.permission.BasePermission;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
315import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
316import com.android.server.pm.permission.PermissionManagerInternal;
317import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
318import com.android.server.pm.permission.PermissionManagerService;
319import com.android.server.pm.permission.PermissionsState;
320import com.android.server.pm.permission.PermissionsState.PermissionState;
321import com.android.server.security.VerityUtils;
322import com.android.server.storage.DeviceStorageMonitorInternal;
323
324import dalvik.system.CloseGuard;
325import dalvik.system.VMRuntime;
326
327import libcore.io.IoUtils;
328
329import org.xmlpull.v1.XmlPullParser;
330import org.xmlpull.v1.XmlPullParserException;
331import org.xmlpull.v1.XmlSerializer;
332
333import java.io.BufferedOutputStream;
334import java.io.ByteArrayInputStream;
335import java.io.ByteArrayOutputStream;
336import java.io.File;
337import java.io.FileDescriptor;
338import java.io.FileInputStream;
339import java.io.FileOutputStream;
340import java.io.FilenameFilter;
341import java.io.IOException;
342import java.io.PrintWriter;
343import java.lang.annotation.Retention;
344import java.lang.annotation.RetentionPolicy;
345import java.nio.charset.StandardCharsets;
346import java.security.DigestException;
347import java.security.DigestInputStream;
348import java.security.MessageDigest;
349import java.security.NoSuchAlgorithmException;
350import java.security.PublicKey;
351import java.security.SecureRandom;
352import java.security.cert.CertificateException;
353import java.util.ArrayList;
354import java.util.Arrays;
355import java.util.Collection;
356import java.util.Collections;
357import java.util.Comparator;
358import java.util.HashMap;
359import java.util.HashSet;
360import java.util.Iterator;
361import java.util.LinkedHashSet;
362import java.util.List;
363import java.util.Map;
364import java.util.Objects;
365import java.util.Set;
366import java.util.concurrent.CountDownLatch;
367import java.util.concurrent.Future;
368import java.util.concurrent.TimeUnit;
369import java.util.concurrent.atomic.AtomicBoolean;
370import java.util.concurrent.atomic.AtomicInteger;
371
372/**
373 * Keep track of all those APKs everywhere.
374 * <p>
375 * Internally there are two important locks:
376 * <ul>
377 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
378 * and other related state. It is a fine-grained lock that should only be held
379 * momentarily, as it's one of the most contended locks in the system.
380 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
381 * operations typically involve heavy lifting of application data on disk. Since
382 * {@code installd} is single-threaded, and it's operations can often be slow,
383 * this lock should never be acquired while already holding {@link #mPackages}.
384 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
385 * holding {@link #mInstallLock}.
386 * </ul>
387 * Many internal methods rely on the caller to hold the appropriate locks, and
388 * this contract is expressed through method name suffixes:
389 * <ul>
390 * <li>fooLI(): the caller must hold {@link #mInstallLock}
391 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
392 * being modified must be frozen
393 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
394 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
395 * </ul>
396 * <p>
397 * Because this class is very central to the platform's security; please run all
398 * CTS and unit tests whenever making modifications:
399 *
400 * <pre>
401 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
402 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
403 * </pre>
404 */
405public class PackageManagerService extends IPackageManager.Stub
406        implements PackageSender {
407    static final String TAG = "PackageManager";
408    public static final boolean DEBUG_SETTINGS = false;
409    static final boolean DEBUG_PREFERRED = false;
410    static final boolean DEBUG_UPGRADE = false;
411    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
412    private static final boolean DEBUG_BACKUP = false;
413    public static final boolean DEBUG_INSTALL = false;
414    public static final boolean DEBUG_REMOVE = true;
415    private static final boolean DEBUG_BROADCASTS = false;
416    private static final boolean DEBUG_SHOW_INFO = false;
417    private static final boolean DEBUG_PACKAGE_INFO = false;
418    private static final boolean DEBUG_INTENT_MATCHING = false;
419    public static final boolean DEBUG_PACKAGE_SCANNING = false;
420    private static final boolean DEBUG_VERIFY = false;
421    private static final boolean DEBUG_FILTERS = false;
422    public static final boolean DEBUG_PERMISSIONS = false;
423    private static final boolean DEBUG_SHARED_LIBRARIES = false;
424    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
425
426    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
427    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
428    // user, but by default initialize to this.
429    public static final boolean DEBUG_DEXOPT = false;
430
431    private static final boolean DEBUG_ABI_SELECTION = false;
432    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
433    private static final boolean DEBUG_TRIAGED_MISSING = false;
434    private static final boolean DEBUG_APP_DATA = false;
435
436    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
437    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
438
439    private static final boolean HIDE_EPHEMERAL_APIS = false;
440
441    private static final boolean ENABLE_FREE_CACHE_V2 =
442            SystemProperties.getBoolean("fw.free_cache_v2", true);
443
444    private static final int RADIO_UID = Process.PHONE_UID;
445    private static final int LOG_UID = Process.LOG_UID;
446    private static final int NFC_UID = Process.NFC_UID;
447    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
448    private static final int SHELL_UID = Process.SHELL_UID;
449    private static final int SE_UID = Process.SE_UID;
450
451    // Suffix used during package installation when copying/moving
452    // package apks to install directory.
453    private static final String INSTALL_PACKAGE_SUFFIX = "-";
454
455    static final int SCAN_NO_DEX = 1<<0;
456    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
457    static final int SCAN_NEW_INSTALL = 1<<2;
458    static final int SCAN_UPDATE_TIME = 1<<3;
459    static final int SCAN_BOOTING = 1<<4;
460    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
461    static final int SCAN_REQUIRE_KNOWN = 1<<7;
462    static final int SCAN_MOVE = 1<<8;
463    static final int SCAN_INITIAL = 1<<9;
464    static final int SCAN_CHECK_ONLY = 1<<10;
465    static final int SCAN_DONT_KILL_APP = 1<<11;
466    static final int SCAN_IGNORE_FROZEN = 1<<12;
467    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
468    static final int SCAN_AS_INSTANT_APP = 1<<14;
469    static final int SCAN_AS_FULL_APP = 1<<15;
470    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
471    static final int SCAN_AS_SYSTEM = 1<<17;
472    static final int SCAN_AS_PRIVILEGED = 1<<18;
473    static final int SCAN_AS_OEM = 1<<19;
474    static final int SCAN_AS_VENDOR = 1<<20;
475    static final int SCAN_AS_PRODUCT = 1<<21;
476
477    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
478            SCAN_NO_DEX,
479            SCAN_UPDATE_SIGNATURE,
480            SCAN_NEW_INSTALL,
481            SCAN_UPDATE_TIME,
482            SCAN_BOOTING,
483            SCAN_DELETE_DATA_ON_FAILURES,
484            SCAN_REQUIRE_KNOWN,
485            SCAN_MOVE,
486            SCAN_INITIAL,
487            SCAN_CHECK_ONLY,
488            SCAN_DONT_KILL_APP,
489            SCAN_IGNORE_FROZEN,
490            SCAN_FIRST_BOOT_OR_UPGRADE,
491            SCAN_AS_INSTANT_APP,
492            SCAN_AS_FULL_APP,
493            SCAN_AS_VIRTUAL_PRELOAD,
494    })
495    @Retention(RetentionPolicy.SOURCE)
496    public @interface ScanFlags {}
497
498    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
499    /** Extension of the compressed packages */
500    public final static String COMPRESSED_EXTENSION = ".gz";
501    /** Suffix of stub packages on the system partition */
502    public final static String STUB_SUFFIX = "-Stub";
503
504    private static final int[] EMPTY_INT_ARRAY = new int[0];
505
506    private static final int TYPE_UNKNOWN = 0;
507    private static final int TYPE_ACTIVITY = 1;
508    private static final int TYPE_RECEIVER = 2;
509    private static final int TYPE_SERVICE = 3;
510    private static final int TYPE_PROVIDER = 4;
511    @IntDef(prefix = { "TYPE_" }, value = {
512            TYPE_UNKNOWN,
513            TYPE_ACTIVITY,
514            TYPE_RECEIVER,
515            TYPE_SERVICE,
516            TYPE_PROVIDER,
517    })
518    @Retention(RetentionPolicy.SOURCE)
519    public @interface ComponentType {}
520
521    /**
522     * Timeout (in milliseconds) after which the watchdog should declare that
523     * our handler thread is wedged.  The usual default for such things is one
524     * minute but we sometimes do very lengthy I/O operations on this thread,
525     * such as installing multi-gigabyte applications, so ours needs to be longer.
526     */
527    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
528
529    /**
530     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
531     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
532     * settings entry if available, otherwise we use the hardcoded default.  If it's been
533     * more than this long since the last fstrim, we force one during the boot sequence.
534     *
535     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
536     * one gets run at the next available charging+idle time.  This final mandatory
537     * no-fstrim check kicks in only of the other scheduling criteria is never met.
538     */
539    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
540
541    /**
542     * Whether verification is enabled by default.
543     */
544    private static final boolean DEFAULT_VERIFY_ENABLE = true;
545
546    /**
547     * The default maximum time to wait for the verification agent to return in
548     * milliseconds.
549     */
550    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
551
552    /**
553     * The default response for package verification timeout.
554     *
555     * This can be either PackageManager.VERIFICATION_ALLOW or
556     * PackageManager.VERIFICATION_REJECT.
557     */
558    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
559
560    public static final String PLATFORM_PACKAGE_NAME = "android";
561
562    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
563
564    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
565            DEFAULT_CONTAINER_PACKAGE,
566            "com.android.defcontainer.DefaultContainerService");
567
568    private static final String KILL_APP_REASON_GIDS_CHANGED =
569            "permission grant or revoke changed gids";
570
571    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
572            "permissions revoked";
573
574    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
575
576    private static final String PACKAGE_SCHEME = "package";
577
578    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
579
580    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
581
582    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
583
584    /** Canonical intent used to identify what counts as a "web browser" app */
585    private static final Intent sBrowserIntent;
586    static {
587        sBrowserIntent = new Intent();
588        sBrowserIntent.setAction(Intent.ACTION_VIEW);
589        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
590        sBrowserIntent.setData(Uri.parse("http:"));
591        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
592    }
593
594    /**
595     * The set of all protected actions [i.e. those actions for which a high priority
596     * intent filter is disallowed].
597     */
598    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
599    static {
600        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
601        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
602        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
603        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
604    }
605
606    // Compilation reasons.
607    public static final int REASON_UNKNOWN = -1;
608    public static final int REASON_FIRST_BOOT = 0;
609    public static final int REASON_BOOT = 1;
610    public static final int REASON_INSTALL = 2;
611    public static final int REASON_BACKGROUND_DEXOPT = 3;
612    public static final int REASON_AB_OTA = 4;
613    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
614    public static final int REASON_SHARED = 6;
615
616    public static final int REASON_LAST = REASON_SHARED;
617
618    /**
619     * Version number for the package parser cache. Increment this whenever the format or
620     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
621     */
622    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
623
624    /**
625     * Whether the package parser cache is enabled.
626     */
627    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
628
629    /**
630     * Permissions required in order to receive instant application lifecycle broadcasts.
631     */
632    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
633            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
634
635    final ServiceThread mHandlerThread;
636
637    final PackageHandler mHandler;
638
639    private final ProcessLoggingHandler mProcessLoggingHandler;
640
641    /**
642     * Messages for {@link #mHandler} that need to wait for system ready before
643     * being dispatched.
644     */
645    private ArrayList<Message> mPostSystemReadyMessages;
646
647    final int mSdkVersion = Build.VERSION.SDK_INT;
648
649    final Context mContext;
650    final boolean mFactoryTest;
651    final boolean mOnlyCore;
652    final DisplayMetrics mMetrics;
653    final int mDefParseFlags;
654    final String[] mSeparateProcesses;
655    final boolean mIsUpgrade;
656    final boolean mIsPreNUpgrade;
657    final boolean mIsPreNMR1Upgrade;
658
659    // Have we told the Activity Manager to whitelist the default container service by uid yet?
660    @GuardedBy("mPackages")
661    boolean mDefaultContainerWhitelisted = false;
662
663    @GuardedBy("mPackages")
664    private boolean mDexOptDialogShown;
665
666    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
667    // LOCK HELD.  Can be called with mInstallLock held.
668    @GuardedBy("mInstallLock")
669    final Installer mInstaller;
670
671    /** Directory where installed applications are stored */
672    private static final File sAppInstallDir =
673            new File(Environment.getDataDirectory(), "app");
674    /** Directory where installed application's 32-bit native libraries are copied. */
675    private static final File sAppLib32InstallDir =
676            new File(Environment.getDataDirectory(), "app-lib");
677    /** Directory where code and non-resource assets of forward-locked applications are stored */
678    private static final File sDrmAppPrivateInstallDir =
679            new File(Environment.getDataDirectory(), "app-private");
680
681    // ----------------------------------------------------------------
682
683    // Lock for state used when installing and doing other long running
684    // operations.  Methods that must be called with this lock held have
685    // the suffix "LI".
686    final Object mInstallLock = new Object();
687
688    // ----------------------------------------------------------------
689
690    // Keys are String (package name), values are Package.  This also serves
691    // as the lock for the global state.  Methods that must be called with
692    // this lock held have the prefix "LP".
693    @GuardedBy("mPackages")
694    final ArrayMap<String, PackageParser.Package> mPackages =
695            new ArrayMap<String, PackageParser.Package>();
696
697    final ArrayMap<String, Set<String>> mKnownCodebase =
698            new ArrayMap<String, Set<String>>();
699
700    // Keys are isolated uids and values are the uid of the application
701    // that created the isolated proccess.
702    @GuardedBy("mPackages")
703    final SparseIntArray mIsolatedOwners = new SparseIntArray();
704
705    /**
706     * Tracks new system packages [received in an OTA] that we expect to
707     * find updated user-installed versions. Keys are package name, values
708     * are package location.
709     */
710    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
711    /**
712     * Tracks high priority intent filters for protected actions. During boot, certain
713     * filter actions are protected and should never be allowed to have a high priority
714     * intent filter for them. However, there is one, and only one exception -- the
715     * setup wizard. It must be able to define a high priority intent filter for these
716     * actions to ensure there are no escapes from the wizard. We need to delay processing
717     * of these during boot as we need to look at all of the system packages in order
718     * to know which component is the setup wizard.
719     */
720    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
721    /**
722     * Whether or not processing protected filters should be deferred.
723     */
724    private boolean mDeferProtectedFilters = true;
725
726    /**
727     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
728     */
729    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
730    /**
731     * Whether or not system app permissions should be promoted from install to runtime.
732     */
733    boolean mPromoteSystemApps;
734
735    @GuardedBy("mPackages")
736    final Settings mSettings;
737
738    /**
739     * Set of package names that are currently "frozen", which means active
740     * surgery is being done on the code/data for that package. The platform
741     * will refuse to launch frozen packages to avoid race conditions.
742     *
743     * @see PackageFreezer
744     */
745    @GuardedBy("mPackages")
746    final ArraySet<String> mFrozenPackages = new ArraySet<>();
747
748    final ProtectedPackages mProtectedPackages;
749
750    @GuardedBy("mLoadedVolumes")
751    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
752
753    boolean mFirstBoot;
754
755    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
756
757    @GuardedBy("mAvailableFeatures")
758    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
759
760    private final InstantAppRegistry mInstantAppRegistry;
761
762    @GuardedBy("mPackages")
763    int mChangedPackagesSequenceNumber;
764    /**
765     * List of changed [installed, removed or updated] packages.
766     * mapping from user id -> sequence number -> package name
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
770    /**
771     * The sequence number of the last change to a package.
772     * mapping from user id -> package name -> sequence number
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
776
777    @GuardedBy("mPackages")
778    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
779
780    class PackageParserCallback implements PackageParser.Callback {
781        @Override public final boolean hasFeature(String feature) {
782            return PackageManagerService.this.hasSystemFeature(feature, 0);
783        }
784
785        final List<PackageParser.Package> getStaticOverlayPackages(
786                Collection<PackageParser.Package> allPackages, String targetPackageName) {
787            if ("android".equals(targetPackageName)) {
788                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
789                // native AssetManager.
790                return null;
791            }
792
793            List<PackageParser.Package> overlayPackages = null;
794            for (PackageParser.Package p : allPackages) {
795                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
796                    if (overlayPackages == null) {
797                        overlayPackages = new ArrayList<PackageParser.Package>();
798                    }
799                    overlayPackages.add(p);
800                }
801            }
802            if (overlayPackages != null) {
803                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
804                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
805                        return p1.mOverlayPriority - p2.mOverlayPriority;
806                    }
807                };
808                Collections.sort(overlayPackages, cmp);
809            }
810            return overlayPackages;
811        }
812
813        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
814                String targetPath) {
815            if (overlayPackages == null || overlayPackages.isEmpty()) {
816                return null;
817            }
818            List<String> overlayPathList = null;
819            for (PackageParser.Package overlayPackage : overlayPackages) {
820                if (targetPath == null) {
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                    continue;
826                }
827
828                try {
829                    // Creates idmaps for system to parse correctly the Android manifest of the
830                    // target package.
831                    //
832                    // OverlayManagerService will update each of them with a correct gid from its
833                    // target package app id.
834                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
835                            UserHandle.getSharedAppGid(
836                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
837                    if (overlayPathList == null) {
838                        overlayPathList = new ArrayList<String>();
839                    }
840                    overlayPathList.add(overlayPackage.baseCodePath);
841                } catch (InstallerException e) {
842                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
843                            overlayPackage.baseCodePath);
844                }
845            }
846            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
847        }
848
849        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            List<PackageParser.Package> overlayPackages;
851            synchronized (mInstallLock) {
852                synchronized (mPackages) {
853                    overlayPackages = getStaticOverlayPackages(
854                            mPackages.values(), targetPackageName);
855                }
856                // It is safe to keep overlayPackages without holding mPackages because static overlay
857                // packages can't be uninstalled or disabled.
858                return getStaticOverlayPaths(overlayPackages, targetPath);
859            }
860        }
861
862        @Override public final String[] getOverlayApks(String targetPackageName) {
863            return getStaticOverlayPaths(targetPackageName, null);
864        }
865
866        @Override public final String[] getOverlayPaths(String targetPackageName,
867                String targetPath) {
868            return getStaticOverlayPaths(targetPackageName, targetPath);
869        }
870    }
871
872    class ParallelPackageParserCallback extends PackageParserCallback {
873        List<PackageParser.Package> mOverlayPackages = null;
874
875        void findStaticOverlayPackages() {
876            synchronized (mPackages) {
877                for (PackageParser.Package p : mPackages.values()) {
878                    if (p.mOverlayIsStatic) {
879                        if (mOverlayPackages == null) {
880                            mOverlayPackages = new ArrayList<PackageParser.Package>();
881                        }
882                        mOverlayPackages.add(p);
883                    }
884                }
885            }
886        }
887
888        @Override
889        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
890            // We can trust mOverlayPackages without holding mPackages because package uninstall
891            // can't happen while running parallel parsing.
892            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
893            // because mInstallLock is held before running parallel parsing.
894            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
895            return mOverlayPackages == null ? null :
896                    getStaticOverlayPaths(
897                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
898                            targetPath);
899        }
900    }
901
902    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
903    final ParallelPackageParserCallback mParallelPackageParserCallback =
904            new ParallelPackageParserCallback();
905
906    public static final class SharedLibraryEntry {
907        public final @Nullable String path;
908        public final @Nullable String apk;
909        public final @NonNull SharedLibraryInfo info;
910
911        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
912                String declaringPackageName, long declaringPackageVersionCode) {
913            path = _path;
914            apk = _apk;
915            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
916                    declaringPackageName, declaringPackageVersionCode), null);
917        }
918    }
919
920    // Currently known shared libraries.
921    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
922    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
923            new ArrayMap<>();
924
925    // All available activities, for your resolving pleasure.
926    final ActivityIntentResolver mActivities =
927            new ActivityIntentResolver();
928
929    // All available receivers, for your resolving pleasure.
930    final ActivityIntentResolver mReceivers =
931            new ActivityIntentResolver();
932
933    // All available services, for your resolving pleasure.
934    final ServiceIntentResolver mServices = new ServiceIntentResolver();
935
936    // All available providers, for your resolving pleasure.
937    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
938
939    // Mapping from provider base names (first directory in content URI codePath)
940    // to the provider information.
941    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
942            new ArrayMap<String, PackageParser.Provider>();
943
944    // Mapping from instrumentation class names to info about them.
945    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
946            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
947
948    // Packages whose data we have transfered into another package, thus
949    // should no longer exist.
950    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
951
952    // Broadcast actions that are only available to the system.
953    @GuardedBy("mProtectedBroadcasts")
954    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
955
956    /** List of packages waiting for verification. */
957    final SparseArray<PackageVerificationState> mPendingVerification
958            = new SparseArray<PackageVerificationState>();
959
960    final PackageInstallerService mInstallerService;
961
962    final ArtManagerService mArtManagerService;
963
964    private final PackageDexOptimizer mPackageDexOptimizer;
965    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
966    // is used by other apps).
967    private final DexManager mDexManager;
968
969    private AtomicInteger mNextMoveId = new AtomicInteger();
970    private final MoveCallbacks mMoveCallbacks;
971
972    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
973
974    // Cache of users who need badging.
975    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
976
977    /** Token for keys in mPendingVerification. */
978    private int mPendingVerificationToken = 0;
979
980    volatile boolean mSystemReady;
981    volatile boolean mSafeMode;
982    volatile boolean mHasSystemUidErrors;
983    private volatile boolean mWebInstantAppsDisabled;
984
985    ApplicationInfo mAndroidApplication;
986    final ActivityInfo mResolveActivity = new ActivityInfo();
987    final ResolveInfo mResolveInfo = new ResolveInfo();
988    ComponentName mResolveComponentName;
989    PackageParser.Package mPlatformPackage;
990    ComponentName mCustomResolverComponentName;
991
992    boolean mResolverReplaced = false;
993
994    private final @Nullable ComponentName mIntentFilterVerifierComponent;
995    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
996
997    private int mIntentFilterVerificationToken = 0;
998
999    /** The service connection to the ephemeral resolver */
1000    final InstantAppResolverConnection mInstantAppResolverConnection;
1001    /** Component used to show resolver settings for Instant Apps */
1002    final ComponentName mInstantAppResolverSettingsComponent;
1003
1004    /** Activity used to install instant applications */
1005    ActivityInfo mInstantAppInstallerActivity;
1006    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1007
1008    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1009            = new SparseArray<IntentFilterVerificationState>();
1010
1011    // TODO remove this and go through mPermissonManager directly
1012    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1013    private final PermissionManagerInternal mPermissionManager;
1014
1015    // List of packages names to keep cached, even if they are uninstalled for all users
1016    private List<String> mKeepUninstalledPackages;
1017
1018    private UserManagerInternal mUserManagerInternal;
1019    private ActivityManagerInternal mActivityManagerInternal;
1020
1021    private DeviceIdleController.LocalService mDeviceIdleController;
1022
1023    private File mCacheDir;
1024
1025    private Future<?> mPrepareAppDataFuture;
1026
1027    private static class IFVerificationParams {
1028        PackageParser.Package pkg;
1029        boolean replacing;
1030        int userId;
1031        int verifierUid;
1032
1033        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1034                int _userId, int _verifierUid) {
1035            pkg = _pkg;
1036            replacing = _replacing;
1037            userId = _userId;
1038            replacing = _replacing;
1039            verifierUid = _verifierUid;
1040        }
1041    }
1042
1043    private interface IntentFilterVerifier<T extends IntentFilter> {
1044        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1045                                               T filter, String packageName);
1046        void startVerifications(int userId);
1047        void receiveVerificationResponse(int verificationId);
1048    }
1049
1050    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1051        private Context mContext;
1052        private ComponentName mIntentFilterVerifierComponent;
1053        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1054
1055        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1056            mContext = context;
1057            mIntentFilterVerifierComponent = verifierComponent;
1058        }
1059
1060        private String getDefaultScheme() {
1061            return IntentFilter.SCHEME_HTTPS;
1062        }
1063
1064        @Override
1065        public void startVerifications(int userId) {
1066            // Launch verifications requests
1067            int count = mCurrentIntentFilterVerifications.size();
1068            for (int n=0; n<count; n++) {
1069                int verificationId = mCurrentIntentFilterVerifications.get(n);
1070                final IntentFilterVerificationState ivs =
1071                        mIntentFilterVerificationStates.get(verificationId);
1072
1073                String packageName = ivs.getPackageName();
1074
1075                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1076                final int filterCount = filters.size();
1077                ArraySet<String> domainsSet = new ArraySet<>();
1078                for (int m=0; m<filterCount; m++) {
1079                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1080                    domainsSet.addAll(filter.getHostsList());
1081                }
1082                synchronized (mPackages) {
1083                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1084                            packageName, domainsSet) != null) {
1085                        scheduleWriteSettingsLocked();
1086                    }
1087                }
1088                sendVerificationRequest(verificationId, ivs);
1089            }
1090            mCurrentIntentFilterVerifications.clear();
1091        }
1092
1093        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1094            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1097                    verificationId);
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1100                    getDefaultScheme());
1101            verificationIntent.putExtra(
1102                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1103                    ivs.getHostsString());
1104            verificationIntent.putExtra(
1105                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1106                    ivs.getPackageName());
1107            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1108            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1109
1110            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1111            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1112                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1113                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1114
1115            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1117                    "Sending IntentFilter verification broadcast");
1118        }
1119
1120        public void receiveVerificationResponse(int verificationId) {
1121            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1122
1123            final boolean verified = ivs.isVerified();
1124
1125            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1126            final int count = filters.size();
1127            if (DEBUG_DOMAIN_VERIFICATION) {
1128                Slog.i(TAG, "Received verification response " + verificationId
1129                        + " for " + count + " filters, verified=" + verified);
1130            }
1131            for (int n=0; n<count; n++) {
1132                PackageParser.ActivityIntentInfo filter = filters.get(n);
1133                filter.setVerified(verified);
1134
1135                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1136                        + " verified with result:" + verified + " and hosts:"
1137                        + ivs.getHostsString());
1138            }
1139
1140            mIntentFilterVerificationStates.remove(verificationId);
1141
1142            final String packageName = ivs.getPackageName();
1143            IntentFilterVerificationInfo ivi = null;
1144
1145            synchronized (mPackages) {
1146                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1147            }
1148            if (ivi == null) {
1149                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1150                        + verificationId + " packageName:" + packageName);
1151                return;
1152            }
1153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1154                    "Updating IntentFilterVerificationInfo for package " + packageName
1155                            +" verificationId:" + verificationId);
1156
1157            synchronized (mPackages) {
1158                if (verified) {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1160                } else {
1161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1162                }
1163                scheduleWriteSettingsLocked();
1164
1165                final int userId = ivs.getUserId();
1166                if (userId != UserHandle.USER_ALL) {
1167                    final int userStatus =
1168                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1169
1170                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1171                    boolean needUpdate = false;
1172
1173                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1174                    // already been set by the User thru the Disambiguation dialog
1175                    switch (userStatus) {
1176                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1177                            if (verified) {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1179                            } else {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1181                            }
1182                            needUpdate = true;
1183                            break;
1184
1185                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1186                            if (verified) {
1187                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1188                                needUpdate = true;
1189                            }
1190                            break;
1191
1192                        default:
1193                            // Nothing to do
1194                    }
1195
1196                    if (needUpdate) {
1197                        mSettings.updateIntentFilterVerificationStatusLPw(
1198                                packageName, updatedStatus, userId);
1199                        scheduleWritePackageRestrictionsLocked(userId);
1200                    }
1201                }
1202            }
1203        }
1204
1205        @Override
1206        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1207                    ActivityIntentInfo filter, String packageName) {
1208            if (!hasValidDomains(filter)) {
1209                return false;
1210            }
1211            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1212            if (ivs == null) {
1213                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1214                        packageName);
1215            }
1216            if (DEBUG_DOMAIN_VERIFICATION) {
1217                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1218            }
1219            ivs.addFilter(filter);
1220            return true;
1221        }
1222
1223        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1224                int userId, int verificationId, String packageName) {
1225            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1226                    verifierUid, userId, packageName);
1227            ivs.setPendingState();
1228            synchronized (mPackages) {
1229                mIntentFilterVerificationStates.append(verificationId, ivs);
1230                mCurrentIntentFilterVerifications.add(verificationId);
1231            }
1232            return ivs;
1233        }
1234    }
1235
1236    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1237        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1238                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1239                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1240    }
1241
1242    // Set of pending broadcasts for aggregating enable/disable of components.
1243    static class PendingPackageBroadcasts {
1244        // for each user id, a map of <package name -> components within that package>
1245        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1246
1247        public PendingPackageBroadcasts() {
1248            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1249        }
1250
1251        public ArrayList<String> get(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            return packages.get(packageName);
1254        }
1255
1256        public void put(int userId, String packageName, ArrayList<String> components) {
1257            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1258            packages.put(packageName, components);
1259        }
1260
1261        public void remove(int userId, String packageName) {
1262            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1263            if (packages != null) {
1264                packages.remove(packageName);
1265            }
1266        }
1267
1268        public void remove(int userId) {
1269            mUidMap.remove(userId);
1270        }
1271
1272        public int userIdCount() {
1273            return mUidMap.size();
1274        }
1275
1276        public int userIdAt(int n) {
1277            return mUidMap.keyAt(n);
1278        }
1279
1280        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1281            return mUidMap.get(userId);
1282        }
1283
1284        public int size() {
1285            // total number of pending broadcast entries across all userIds
1286            int num = 0;
1287            for (int i = 0; i< mUidMap.size(); i++) {
1288                num += mUidMap.valueAt(i).size();
1289            }
1290            return num;
1291        }
1292
1293        public void clear() {
1294            mUidMap.clear();
1295        }
1296
1297        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1298            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1299            if (map == null) {
1300                map = new ArrayMap<String, ArrayList<String>>();
1301                mUidMap.put(userId, map);
1302            }
1303            return map;
1304        }
1305    }
1306    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1307
1308    // Service Connection to remote media container service to copy
1309    // package uri's from external media onto secure containers
1310    // or internal storage.
1311    private IMediaContainerService mContainerService = null;
1312
1313    static final int SEND_PENDING_BROADCAST = 1;
1314    static final int MCS_BOUND = 3;
1315    static final int END_COPY = 4;
1316    static final int INIT_COPY = 5;
1317    static final int MCS_UNBIND = 6;
1318    static final int START_CLEANING_PACKAGE = 7;
1319    static final int FIND_INSTALL_LOC = 8;
1320    static final int POST_INSTALL = 9;
1321    static final int MCS_RECONNECT = 10;
1322    static final int MCS_GIVE_UP = 11;
1323    static final int WRITE_SETTINGS = 13;
1324    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1325    static final int PACKAGE_VERIFIED = 15;
1326    static final int CHECK_PENDING_VERIFICATION = 16;
1327    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1328    static final int INTENT_FILTER_VERIFIED = 18;
1329    static final int WRITE_PACKAGE_LIST = 19;
1330    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1331    static final int DEF_CONTAINER_BIND = 21;
1332
1333    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1334
1335    // Delay time in millisecs
1336    static final int BROADCAST_DELAY = 10 * 1000;
1337
1338    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1339            2 * 60 * 60 * 1000L; /* two hours */
1340
1341    static UserManagerService sUserManager;
1342
1343    // Stores a list of users whose package restrictions file needs to be updated
1344    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1345
1346    final private DefaultContainerConnection mDefContainerConn =
1347            new DefaultContainerConnection();
1348    class DefaultContainerConnection implements ServiceConnection {
1349        public void onServiceConnected(ComponentName name, IBinder service) {
1350            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1351            final IMediaContainerService imcs = IMediaContainerService.Stub
1352                    .asInterface(Binder.allowBlocking(service));
1353            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1354        }
1355
1356        public void onServiceDisconnected(ComponentName name) {
1357            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1358        }
1359    }
1360
1361    // Recordkeeping of restore-after-install operations that are currently in flight
1362    // between the Package Manager and the Backup Manager
1363    static class PostInstallData {
1364        public InstallArgs args;
1365        public PackageInstalledInfo res;
1366
1367        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1368            args = _a;
1369            res = _r;
1370        }
1371    }
1372
1373    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1374    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1375
1376    // XML tags for backup/restore of various bits of state
1377    private static final String TAG_PREFERRED_BACKUP = "pa";
1378    private static final String TAG_DEFAULT_APPS = "da";
1379    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1380
1381    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1382    private static final String TAG_ALL_GRANTS = "rt-grants";
1383    private static final String TAG_GRANT = "grant";
1384    private static final String ATTR_PACKAGE_NAME = "pkg";
1385
1386    private static final String TAG_PERMISSION = "perm";
1387    private static final String ATTR_PERMISSION_NAME = "name";
1388    private static final String ATTR_IS_GRANTED = "g";
1389    private static final String ATTR_USER_SET = "set";
1390    private static final String ATTR_USER_FIXED = "fixed";
1391    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1392
1393    // System/policy permission grants are not backed up
1394    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_POLICY_FIXED
1396            | FLAG_PERMISSION_SYSTEM_FIXED
1397            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1398
1399    // And we back up these user-adjusted states
1400    private static final int USER_RUNTIME_GRANT_MASK =
1401            FLAG_PERMISSION_USER_SET
1402            | FLAG_PERMISSION_USER_FIXED
1403            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1404
1405    final @Nullable String mRequiredVerifierPackage;
1406    final @NonNull String mRequiredInstallerPackage;
1407    final @NonNull String mRequiredUninstallerPackage;
1408    final @Nullable String mSetupWizardPackage;
1409    final @Nullable String mStorageManagerPackage;
1410    final @Nullable String mSystemTextClassifierPackage;
1411    final @NonNull String mServicesSystemSharedLibraryPackageName;
1412    final @NonNull String mSharedSystemSharedLibraryPackageName;
1413
1414    private final PackageUsage mPackageUsage = new PackageUsage();
1415    private final CompilerStats mCompilerStats = new CompilerStats();
1416
1417    class PackageHandler extends Handler {
1418        private boolean mBound = false;
1419        final ArrayList<HandlerParams> mPendingInstalls =
1420            new ArrayList<HandlerParams>();
1421
1422        private boolean connectToService() {
1423            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1424            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1426            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1427                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1428                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429                mBound = true;
1430                return true;
1431            }
1432            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            return false;
1434        }
1435
1436        private void disconnectService() {
1437            mContainerService = null;
1438            mBound = false;
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1440            mContext.unbindService(mDefContainerConn);
1441            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1442        }
1443
1444        PackageHandler(Looper looper) {
1445            super(looper);
1446        }
1447
1448        public void handleMessage(Message msg) {
1449            try {
1450                doHandleMessage(msg);
1451            } finally {
1452                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1453            }
1454        }
1455
1456        void doHandleMessage(Message msg) {
1457            switch (msg.what) {
1458                case DEF_CONTAINER_BIND:
1459                    if (!mBound) {
1460                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1461                                System.identityHashCode(mHandler));
1462                        if (!connectToService()) {
1463                            Slog.e(TAG, "Failed to bind to media container service");
1464                        }
1465                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1466                                System.identityHashCode(mHandler));
1467                    }
1468                    break;
1469                case INIT_COPY: {
1470                    HandlerParams params = (HandlerParams) msg.obj;
1471                    int idx = mPendingInstalls.size();
1472                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1473                    // If a bind was already initiated we dont really
1474                    // need to do anything. The pending install
1475                    // will be processed later on.
1476                    if (!mBound) {
1477                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1478                                System.identityHashCode(mHandler));
1479                        // If this is the only one pending we might
1480                        // have to bind to the service again.
1481                        if (!connectToService()) {
1482                            Slog.e(TAG, "Failed to bind to media container service");
1483                            params.serviceError();
1484                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1485                                    System.identityHashCode(mHandler));
1486                            if (params.traceMethod != null) {
1487                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1488                                        params.traceCookie);
1489                            }
1490                            return;
1491                        } else {
1492                            // Once we bind to the service, the first
1493                            // pending request will be processed.
1494                            mPendingInstalls.add(idx, params);
1495                        }
1496                    } else {
1497                        mPendingInstalls.add(idx, params);
1498                        // Already bound to the service. Just make
1499                        // sure we trigger off processing the first request.
1500                        if (idx == 0) {
1501                            mHandler.sendEmptyMessage(MCS_BOUND);
1502                        }
1503                    }
1504                    break;
1505                }
1506                case MCS_BOUND: {
1507                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1508                    if (msg.obj != null) {
1509                        mContainerService = (IMediaContainerService) msg.obj;
1510                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1511                                System.identityHashCode(mHandler));
1512                    }
1513                    if (mContainerService == null) {
1514                        if (!mBound) {
1515                            // Something seriously wrong since we are not bound and we are not
1516                            // waiting for connection. Bail out.
1517                            Slog.e(TAG, "Cannot bind to media container service");
1518                            for (HandlerParams params : mPendingInstalls) {
1519                                // Indicate service bind error
1520                                params.serviceError();
1521                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                                        System.identityHashCode(params));
1523                                if (params.traceMethod != null) {
1524                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1525                                            params.traceMethod, params.traceCookie);
1526                                }
1527                            }
1528                            mPendingInstalls.clear();
1529                        } else {
1530                            Slog.w(TAG, "Waiting to connect to media container service");
1531                        }
1532                    } else if (mPendingInstalls.size() > 0) {
1533                        HandlerParams params = mPendingInstalls.get(0);
1534                        if (params != null) {
1535                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1536                                    System.identityHashCode(params));
1537                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1538                            if (params.startCopy()) {
1539                                // We are done...  look for more work or to
1540                                // go idle.
1541                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                        "Checking for more work or unbind...");
1543                                // Delete pending install
1544                                if (mPendingInstalls.size() > 0) {
1545                                    mPendingInstalls.remove(0);
1546                                }
1547                                if (mPendingInstalls.size() == 0) {
1548                                    if (mBound) {
1549                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1550                                                "Posting delayed MCS_UNBIND");
1551                                        removeMessages(MCS_UNBIND);
1552                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1553                                        // Unbind after a little delay, to avoid
1554                                        // continual thrashing.
1555                                        sendMessageDelayed(ubmsg, 10000);
1556                                    }
1557                                } else {
1558                                    // There are more pending requests in queue.
1559                                    // Just post MCS_BOUND message to trigger processing
1560                                    // of next pending install.
1561                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1562                                            "Posting MCS_BOUND for next work");
1563                                    mHandler.sendEmptyMessage(MCS_BOUND);
1564                                }
1565                            }
1566                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1567                        }
1568                    } else {
1569                        // Should never happen ideally.
1570                        Slog.w(TAG, "Empty queue");
1571                    }
1572                    break;
1573                }
1574                case MCS_RECONNECT: {
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1576                    if (mPendingInstalls.size() > 0) {
1577                        if (mBound) {
1578                            disconnectService();
1579                        }
1580                        if (!connectToService()) {
1581                            Slog.e(TAG, "Failed to bind to media container service");
1582                            for (HandlerParams params : mPendingInstalls) {
1583                                // Indicate service bind error
1584                                params.serviceError();
1585                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                                        System.identityHashCode(params));
1587                            }
1588                            mPendingInstalls.clear();
1589                        }
1590                    }
1591                    break;
1592                }
1593                case MCS_UNBIND: {
1594                    // If there is no actual work left, then time to unbind.
1595                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1596
1597                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1598                        if (mBound) {
1599                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1600
1601                            disconnectService();
1602                        }
1603                    } else if (mPendingInstalls.size() > 0) {
1604                        // There are more pending requests in queue.
1605                        // Just post MCS_BOUND message to trigger processing
1606                        // of next pending install.
1607                        mHandler.sendEmptyMessage(MCS_BOUND);
1608                    }
1609
1610                    break;
1611                }
1612                case MCS_GIVE_UP: {
1613                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1614                    HandlerParams params = mPendingInstalls.remove(0);
1615                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1616                            System.identityHashCode(params));
1617                    break;
1618                }
1619                case SEND_PENDING_BROADCAST: {
1620                    String packages[];
1621                    ArrayList<String> components[];
1622                    int size = 0;
1623                    int uids[];
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1625                    synchronized (mPackages) {
1626                        if (mPendingBroadcasts == null) {
1627                            return;
1628                        }
1629                        size = mPendingBroadcasts.size();
1630                        if (size <= 0) {
1631                            // Nothing to be done. Just return
1632                            return;
1633                        }
1634                        packages = new String[size];
1635                        components = new ArrayList[size];
1636                        uids = new int[size];
1637                        int i = 0;  // filling out the above arrays
1638
1639                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1640                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1641                            Iterator<Map.Entry<String, ArrayList<String>>> it
1642                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1643                                            .entrySet().iterator();
1644                            while (it.hasNext() && i < size) {
1645                                Map.Entry<String, ArrayList<String>> ent = it.next();
1646                                packages[i] = ent.getKey();
1647                                components[i] = ent.getValue();
1648                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1649                                uids[i] = (ps != null)
1650                                        ? UserHandle.getUid(packageUserId, ps.appId)
1651                                        : -1;
1652                                i++;
1653                            }
1654                        }
1655                        size = i;
1656                        mPendingBroadcasts.clear();
1657                    }
1658                    // Send broadcasts
1659                    for (int i = 0; i < size; i++) {
1660                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    break;
1664                }
1665                case START_CLEANING_PACKAGE: {
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1667                    final String packageName = (String)msg.obj;
1668                    final int userId = msg.arg1;
1669                    final boolean andCode = msg.arg2 != 0;
1670                    synchronized (mPackages) {
1671                        if (userId == UserHandle.USER_ALL) {
1672                            int[] users = sUserManager.getUserIds();
1673                            for (int user : users) {
1674                                mSettings.addPackageToCleanLPw(
1675                                        new PackageCleanItem(user, packageName, andCode));
1676                            }
1677                        } else {
1678                            mSettings.addPackageToCleanLPw(
1679                                    new PackageCleanItem(userId, packageName, andCode));
1680                        }
1681                    }
1682                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1683                    startCleaningPackages();
1684                } break;
1685                case POST_INSTALL: {
1686                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1687
1688                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1689                    final boolean didRestore = (msg.arg2 != 0);
1690                    mRunningInstalls.delete(msg.arg1);
1691
1692                    if (data != null) {
1693                        InstallArgs args = data.args;
1694                        PackageInstalledInfo parentRes = data.res;
1695
1696                        final boolean grantPermissions = (args.installFlags
1697                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1698                        final boolean killApp = (args.installFlags
1699                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1700                        final boolean virtualPreload = ((args.installFlags
1701                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1702                        final String[] grantedPermissions = args.installGrantPermissions;
1703
1704                        // Handle the parent package
1705                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1706                                virtualPreload, grantedPermissions, didRestore,
1707                                args.installerPackageName, args.observer);
1708
1709                        // Handle the child packages
1710                        final int childCount = (parentRes.addedChildPackages != null)
1711                                ? parentRes.addedChildPackages.size() : 0;
1712                        for (int i = 0; i < childCount; i++) {
1713                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1714                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1715                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1716                                    args.installerPackageName, args.observer);
1717                        }
1718
1719                        // Log tracing if needed
1720                        if (args.traceMethod != null) {
1721                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1722                                    args.traceCookie);
1723                        }
1724                    } else {
1725                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1726                    }
1727
1728                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1729                } break;
1730                case WRITE_SETTINGS: {
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1732                    synchronized (mPackages) {
1733                        removeMessages(WRITE_SETTINGS);
1734                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1735                        mSettings.writeLPr();
1736                        mDirtyUsers.clear();
1737                    }
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                } break;
1740                case WRITE_PACKAGE_RESTRICTIONS: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1744                        for (int userId : mDirtyUsers) {
1745                            mSettings.writePackageRestrictionsLPr(userId);
1746                        }
1747                        mDirtyUsers.clear();
1748                    }
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1750                } break;
1751                case WRITE_PACKAGE_LIST: {
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1753                    synchronized (mPackages) {
1754                        removeMessages(WRITE_PACKAGE_LIST);
1755                        mSettings.writePackageListLPr(msg.arg1);
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case CHECK_PENDING_VERIFICATION: {
1760                    final int verificationId = msg.arg1;
1761                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1762
1763                    if ((state != null) && !state.timeoutExtended()) {
1764                        final InstallArgs args = state.getInstallArgs();
1765                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1766
1767                        Slog.i(TAG, "Verification timed out for " + originUri);
1768                        mPendingVerification.remove(verificationId);
1769
1770                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1771
1772                        final UserHandle user = args.getUser();
1773                        if (getDefaultVerificationResponse(user)
1774                                == PackageManager.VERIFICATION_ALLOW) {
1775                            Slog.i(TAG, "Continuing with installation of " + originUri);
1776                            state.setVerifierResponse(Binder.getCallingUid(),
1777                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1778                            broadcastPackageVerified(verificationId, originUri,
1779                                    PackageManager.VERIFICATION_ALLOW, user);
1780                            try {
1781                                ret = args.copyApk(mContainerService, true);
1782                            } catch (RemoteException e) {
1783                                Slog.e(TAG, "Could not contact the ContainerService");
1784                            }
1785                        } else {
1786                            broadcastPackageVerified(verificationId, originUri,
1787                                    PackageManager.VERIFICATION_REJECT, user);
1788                        }
1789
1790                        Trace.asyncTraceEnd(
1791                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1792
1793                        processPendingInstall(args, ret);
1794                        mHandler.sendEmptyMessage(MCS_UNBIND);
1795                    }
1796                    break;
1797                }
1798                case PACKAGE_VERIFIED: {
1799                    final int verificationId = msg.arg1;
1800
1801                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1802                    if (state == null) {
1803                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1804                        break;
1805                    }
1806
1807                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1808
1809                    state.setVerifierResponse(response.callerUid, response.code);
1810
1811                    if (state.isVerificationComplete()) {
1812                        mPendingVerification.remove(verificationId);
1813
1814                        final InstallArgs args = state.getInstallArgs();
1815                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1816
1817                        int ret;
1818                        if (state.isInstallAllowed()) {
1819                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1820                            broadcastPackageVerified(verificationId, originUri,
1821                                    response.code, state.getInstallArgs().getUser());
1822                            try {
1823                                ret = args.copyApk(mContainerService, true);
1824                            } catch (RemoteException e) {
1825                                Slog.e(TAG, "Could not contact the ContainerService");
1826                            }
1827                        } else {
1828                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1829                        }
1830
1831                        Trace.asyncTraceEnd(
1832                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1833
1834                        processPendingInstall(args, ret);
1835                        mHandler.sendEmptyMessage(MCS_UNBIND);
1836                    }
1837
1838                    break;
1839                }
1840                case START_INTENT_FILTER_VERIFICATIONS: {
1841                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1842                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1843                            params.replacing, params.pkg);
1844                    break;
1845                }
1846                case INTENT_FILTER_VERIFIED: {
1847                    final int verificationId = msg.arg1;
1848
1849                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1850                            verificationId);
1851                    if (state == null) {
1852                        Slog.w(TAG, "Invalid IntentFilter verification token "
1853                                + verificationId + " received");
1854                        break;
1855                    }
1856
1857                    final int userId = state.getUserId();
1858
1859                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1860                            "Processing IntentFilter verification with token:"
1861                            + verificationId + " and userId:" + userId);
1862
1863                    final IntentFilterVerificationResponse response =
1864                            (IntentFilterVerificationResponse) msg.obj;
1865
1866                    state.setVerifierResponse(response.callerUid, response.code);
1867
1868                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1869                            "IntentFilter verification with token:" + verificationId
1870                            + " and userId:" + userId
1871                            + " is settings verifier response with response code:"
1872                            + response.code);
1873
1874                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1875                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1876                                + response.getFailedDomainsString());
1877                    }
1878
1879                    if (state.isVerificationComplete()) {
1880                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1881                    } else {
1882                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1883                                "IntentFilter verification with token:" + verificationId
1884                                + " was not said to be complete");
1885                    }
1886
1887                    break;
1888                }
1889                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1890                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1891                            mInstantAppResolverConnection,
1892                            (InstantAppRequest) msg.obj,
1893                            mInstantAppInstallerActivity,
1894                            mHandler);
1895                }
1896            }
1897        }
1898    }
1899
1900    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1901        @Override
1902        public void onGidsChanged(int appId, int userId) {
1903            mHandler.post(new Runnable() {
1904                @Override
1905                public void run() {
1906                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1907                }
1908            });
1909        }
1910        @Override
1911        public void onPermissionGranted(int uid, int userId) {
1912            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1913
1914            // Not critical; if this is lost, the application has to request again.
1915            synchronized (mPackages) {
1916                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1917            }
1918        }
1919        @Override
1920        public void onInstallPermissionGranted() {
1921            synchronized (mPackages) {
1922                scheduleWriteSettingsLocked();
1923            }
1924        }
1925        @Override
1926        public void onPermissionRevoked(int uid, int userId) {
1927            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1928
1929            synchronized (mPackages) {
1930                // Critical; after this call the application should never have the permission
1931                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1932            }
1933
1934            final int appId = UserHandle.getAppId(uid);
1935            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1936        }
1937        @Override
1938        public void onInstallPermissionRevoked() {
1939            synchronized (mPackages) {
1940                scheduleWriteSettingsLocked();
1941            }
1942        }
1943        @Override
1944        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1945            synchronized (mPackages) {
1946                for (int userId : updatedUserIds) {
1947                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1948                }
1949            }
1950        }
1951        @Override
1952        public void onInstallPermissionUpdated() {
1953            synchronized (mPackages) {
1954                scheduleWriteSettingsLocked();
1955            }
1956        }
1957        @Override
1958        public void onPermissionRemoved() {
1959            synchronized (mPackages) {
1960                mSettings.writeLPr();
1961            }
1962        }
1963    };
1964
1965    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1966            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1967            boolean launchedForRestore, String installerPackage,
1968            IPackageInstallObserver2 installObserver) {
1969        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1970            // Send the removed broadcasts
1971            if (res.removedInfo != null) {
1972                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1973            }
1974
1975            // Now that we successfully installed the package, grant runtime
1976            // permissions if requested before broadcasting the install. Also
1977            // for legacy apps in permission review mode we clear the permission
1978            // review flag which is used to emulate runtime permissions for
1979            // legacy apps.
1980            if (grantPermissions) {
1981                final int callingUid = Binder.getCallingUid();
1982                mPermissionManager.grantRequestedRuntimePermissions(
1983                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1984                        mPermissionCallback);
1985            }
1986
1987            final boolean update = res.removedInfo != null
1988                    && res.removedInfo.removedPackage != null;
1989            final String installerPackageName =
1990                    res.installerPackageName != null
1991                            ? res.installerPackageName
1992                            : res.removedInfo != null
1993                                    ? res.removedInfo.installerPackageName
1994                                    : null;
1995
1996            // If this is the first time we have child packages for a disabled privileged
1997            // app that had no children, we grant requested runtime permissions to the new
1998            // children if the parent on the system image had them already granted.
1999            if (res.pkg.parentPackage != null) {
2000                final int callingUid = Binder.getCallingUid();
2001                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2002                        res.pkg, callingUid, mPermissionCallback);
2003            }
2004
2005            synchronized (mPackages) {
2006                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2007            }
2008
2009            final String packageName = res.pkg.applicationInfo.packageName;
2010
2011            // Determine the set of users who are adding this package for
2012            // the first time vs. those who are seeing an update.
2013            int[] firstUserIds = EMPTY_INT_ARRAY;
2014            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2015            int[] updateUserIds = EMPTY_INT_ARRAY;
2016            int[] instantUserIds = EMPTY_INT_ARRAY;
2017            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2018            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2019            for (int newUser : res.newUsers) {
2020                final boolean isInstantApp = ps.getInstantApp(newUser);
2021                if (allNewUsers) {
2022                    if (isInstantApp) {
2023                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2024                    } else {
2025                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2026                    }
2027                    continue;
2028                }
2029                boolean isNew = true;
2030                for (int origUser : res.origUsers) {
2031                    if (origUser == newUser) {
2032                        isNew = false;
2033                        break;
2034                    }
2035                }
2036                if (isNew) {
2037                    if (isInstantApp) {
2038                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2039                    } else {
2040                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2041                    }
2042                } else {
2043                    if (isInstantApp) {
2044                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2045                    } else {
2046                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2047                    }
2048                }
2049            }
2050
2051            // Send installed broadcasts if the package is not a static shared lib.
2052            if (res.pkg.staticSharedLibName == null) {
2053                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2054
2055                // Send added for users that see the package for the first time
2056                // sendPackageAddedForNewUsers also deals with system apps
2057                int appId = UserHandle.getAppId(res.uid);
2058                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2059                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2060                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2061
2062                // Send added for users that don't see the package for the first time
2063                Bundle extras = new Bundle(1);
2064                extras.putInt(Intent.EXTRA_UID, res.uid);
2065                if (update) {
2066                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2067                }
2068                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2069                        extras, 0 /*flags*/,
2070                        null /*targetPackage*/, null /*finishedReceiver*/,
2071                        updateUserIds, instantUserIds);
2072                if (installerPackageName != null) {
2073                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2074                            extras, 0 /*flags*/,
2075                            installerPackageName, null /*finishedReceiver*/,
2076                            updateUserIds, instantUserIds);
2077                }
2078
2079                // Send replaced for users that don't see the package for the first time
2080                if (update) {
2081                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2082                            packageName, extras, 0 /*flags*/,
2083                            null /*targetPackage*/, null /*finishedReceiver*/,
2084                            updateUserIds, instantUserIds);
2085                    if (installerPackageName != null) {
2086                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2087                                extras, 0 /*flags*/,
2088                                installerPackageName, null /*finishedReceiver*/,
2089                                updateUserIds, instantUserIds);
2090                    }
2091                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2092                            null /*package*/, null /*extras*/, 0 /*flags*/,
2093                            packageName /*targetPackage*/,
2094                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2095                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2096                    // First-install and we did a restore, so we're responsible for the
2097                    // first-launch broadcast.
2098                    if (DEBUG_BACKUP) {
2099                        Slog.i(TAG, "Post-restore of " + packageName
2100                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2101                    }
2102                    sendFirstLaunchBroadcast(packageName, installerPackage,
2103                            firstUserIds, firstInstantUserIds);
2104                }
2105
2106                // Send broadcast package appeared if forward locked/external for all users
2107                // treat asec-hosted packages like removable media on upgrade
2108                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2109                    if (DEBUG_INSTALL) {
2110                        Slog.i(TAG, "upgrading pkg " + res.pkg
2111                                + " is ASEC-hosted -> AVAILABLE");
2112                    }
2113                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2114                    ArrayList<String> pkgList = new ArrayList<>(1);
2115                    pkgList.add(packageName);
2116                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2117                }
2118            }
2119
2120            // Work that needs to happen on first install within each user
2121            if (firstUserIds != null && firstUserIds.length > 0) {
2122                synchronized (mPackages) {
2123                    for (int userId : firstUserIds) {
2124                        // If this app is a browser and it's newly-installed for some
2125                        // users, clear any default-browser state in those users. The
2126                        // app's nature doesn't depend on the user, so we can just check
2127                        // its browser nature in any user and generalize.
2128                        if (packageIsBrowser(packageName, userId)) {
2129                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2130                        }
2131
2132                        // We may also need to apply pending (restored) runtime
2133                        // permission grants within these users.
2134                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2135                    }
2136                }
2137            }
2138
2139            if (allNewUsers && !update) {
2140                notifyPackageAdded(packageName);
2141            }
2142
2143            // Log current value of "unknown sources" setting
2144            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2145                    getUnknownSourcesSettings());
2146
2147            // Remove the replaced package's older resources safely now
2148            // We delete after a gc for applications  on sdcard.
2149            if (res.removedInfo != null && res.removedInfo.args != null) {
2150                Runtime.getRuntime().gc();
2151                synchronized (mInstallLock) {
2152                    res.removedInfo.args.doPostDeleteLI(true);
2153                }
2154            } else {
2155                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2156                // and not block here.
2157                VMRuntime.getRuntime().requestConcurrentGC();
2158            }
2159
2160            // Notify DexManager that the package was installed for new users.
2161            // The updated users should already be indexed and the package code paths
2162            // should not change.
2163            // Don't notify the manager for ephemeral apps as they are not expected to
2164            // survive long enough to benefit of background optimizations.
2165            for (int userId : firstUserIds) {
2166                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2167                // There's a race currently where some install events may interleave with an uninstall.
2168                // This can lead to package info being null (b/36642664).
2169                if (info != null) {
2170                    mDexManager.notifyPackageInstalled(info, userId);
2171                }
2172            }
2173        }
2174
2175        // If someone is watching installs - notify them
2176        if (installObserver != null) {
2177            try {
2178                Bundle extras = extrasForInstallResult(res);
2179                installObserver.onPackageInstalled(res.name, res.returnCode,
2180                        res.returnMsg, extras);
2181            } catch (RemoteException e) {
2182                Slog.i(TAG, "Observer no longer exists.");
2183            }
2184        }
2185    }
2186
2187    private StorageEventListener mStorageListener = new StorageEventListener() {
2188        @Override
2189        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2190            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2191                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2192                    final String volumeUuid = vol.getFsUuid();
2193
2194                    // Clean up any users or apps that were removed or recreated
2195                    // while this volume was missing
2196                    sUserManager.reconcileUsers(volumeUuid);
2197                    reconcileApps(volumeUuid);
2198
2199                    // Clean up any install sessions that expired or were
2200                    // cancelled while this volume was missing
2201                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2202
2203                    loadPrivatePackages(vol);
2204
2205                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2206                    unloadPrivatePackages(vol);
2207                }
2208            }
2209        }
2210
2211        @Override
2212        public void onVolumeForgotten(String fsUuid) {
2213            if (TextUtils.isEmpty(fsUuid)) {
2214                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2215                return;
2216            }
2217
2218            // Remove any apps installed on the forgotten volume
2219            synchronized (mPackages) {
2220                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2221                for (PackageSetting ps : packages) {
2222                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2223                    deletePackageVersioned(new VersionedPackage(ps.name,
2224                            PackageManager.VERSION_CODE_HIGHEST),
2225                            new LegacyPackageDeleteObserver(null).getBinder(),
2226                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2227                    // Try very hard to release any references to this package
2228                    // so we don't risk the system server being killed due to
2229                    // open FDs
2230                    AttributeCache.instance().removePackage(ps.name);
2231                }
2232
2233                mSettings.onVolumeForgotten(fsUuid);
2234                mSettings.writeLPr();
2235            }
2236        }
2237    };
2238
2239    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2240        Bundle extras = null;
2241        switch (res.returnCode) {
2242            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2243                extras = new Bundle();
2244                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2245                        res.origPermission);
2246                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2247                        res.origPackage);
2248                break;
2249            }
2250            case PackageManager.INSTALL_SUCCEEDED: {
2251                extras = new Bundle();
2252                extras.putBoolean(Intent.EXTRA_REPLACING,
2253                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2254                break;
2255            }
2256        }
2257        return extras;
2258    }
2259
2260    void scheduleWriteSettingsLocked() {
2261        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2262            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2263        }
2264    }
2265
2266    void scheduleWritePackageListLocked(int userId) {
2267        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2268            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2269            msg.arg1 = userId;
2270            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2271        }
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2275        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2276        scheduleWritePackageRestrictionsLocked(userId);
2277    }
2278
2279    void scheduleWritePackageRestrictionsLocked(int userId) {
2280        final int[] userIds = (userId == UserHandle.USER_ALL)
2281                ? sUserManager.getUserIds() : new int[]{userId};
2282        for (int nextUserId : userIds) {
2283            if (!sUserManager.exists(nextUserId)) return;
2284            mDirtyUsers.add(nextUserId);
2285            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2286                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2287            }
2288        }
2289    }
2290
2291    public static PackageManagerService main(Context context, Installer installer,
2292            boolean factoryTest, boolean onlyCore) {
2293        // Self-check for initial settings.
2294        PackageManagerServiceCompilerMapping.checkProperties();
2295
2296        PackageManagerService m = new PackageManagerService(context, installer,
2297                factoryTest, onlyCore);
2298        m.enableSystemUserPackages();
2299        ServiceManager.addService("package", m);
2300        final PackageManagerNative pmn = m.new PackageManagerNative();
2301        ServiceManager.addService("package_native", pmn);
2302        return m;
2303    }
2304
2305    private void enableSystemUserPackages() {
2306        if (!UserManager.isSplitSystemUser()) {
2307            return;
2308        }
2309        // For system user, enable apps based on the following conditions:
2310        // - app is whitelisted or belong to one of these groups:
2311        //   -- system app which has no launcher icons
2312        //   -- system app which has INTERACT_ACROSS_USERS permission
2313        //   -- system IME app
2314        // - app is not in the blacklist
2315        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2316        Set<String> enableApps = new ArraySet<>();
2317        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2318                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2319                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2320        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2321        enableApps.addAll(wlApps);
2322        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2323                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2324        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2325        enableApps.removeAll(blApps);
2326        Log.i(TAG, "Applications installed for system user: " + enableApps);
2327        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2328                UserHandle.SYSTEM);
2329        final int allAppsSize = allAps.size();
2330        synchronized (mPackages) {
2331            for (int i = 0; i < allAppsSize; i++) {
2332                String pName = allAps.get(i);
2333                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2334                // Should not happen, but we shouldn't be failing if it does
2335                if (pkgSetting == null) {
2336                    continue;
2337                }
2338                boolean install = enableApps.contains(pName);
2339                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2340                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2341                            + " for system user");
2342                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2343                }
2344            }
2345            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2346        }
2347    }
2348
2349    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2350        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2351                Context.DISPLAY_SERVICE);
2352        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2353    }
2354
2355    /**
2356     * Requests that files preopted on a secondary system partition be copied to the data partition
2357     * if possible.  Note that the actual copying of the files is accomplished by init for security
2358     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2359     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2360     */
2361    private static void requestCopyPreoptedFiles() {
2362        final int WAIT_TIME_MS = 100;
2363        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2364        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2365            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2366            // We will wait for up to 100 seconds.
2367            final long timeStart = SystemClock.uptimeMillis();
2368            final long timeEnd = timeStart + 100 * 1000;
2369            long timeNow = timeStart;
2370            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2371                try {
2372                    Thread.sleep(WAIT_TIME_MS);
2373                } catch (InterruptedException e) {
2374                    // Do nothing
2375                }
2376                timeNow = SystemClock.uptimeMillis();
2377                if (timeNow > timeEnd) {
2378                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2379                    Slog.wtf(TAG, "cppreopt did not finish!");
2380                    break;
2381                }
2382            }
2383
2384            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2385        }
2386    }
2387
2388    public PackageManagerService(Context context, Installer installer,
2389            boolean factoryTest, boolean onlyCore) {
2390        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2391        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2392        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2393                SystemClock.uptimeMillis());
2394
2395        if (mSdkVersion <= 0) {
2396            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2397        }
2398
2399        mContext = context;
2400
2401        mFactoryTest = factoryTest;
2402        mOnlyCore = onlyCore;
2403        mMetrics = new DisplayMetrics();
2404        mInstaller = installer;
2405
2406        // Create sub-components that provide services / data. Order here is important.
2407        synchronized (mInstallLock) {
2408        synchronized (mPackages) {
2409            // Expose private service for system components to use.
2410            LocalServices.addService(
2411                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2412            sUserManager = new UserManagerService(context, this,
2413                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2414            mPermissionManager = PermissionManagerService.create(context,
2415                    new DefaultPermissionGrantedCallback() {
2416                        @Override
2417                        public void onDefaultRuntimePermissionsGranted(int userId) {
2418                            synchronized(mPackages) {
2419                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2420                            }
2421                        }
2422                    }, mPackages /*externalLock*/);
2423            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2424            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2425        }
2426        }
2427        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2440                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2441
2442        String separateProcesses = SystemProperties.get("debug.separate_processes");
2443        if (separateProcesses != null && separateProcesses.length() > 0) {
2444            if ("*".equals(separateProcesses)) {
2445                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2446                mSeparateProcesses = null;
2447                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2448            } else {
2449                mDefParseFlags = 0;
2450                mSeparateProcesses = separateProcesses.split(",");
2451                Slog.w(TAG, "Running with debug.separate_processes: "
2452                        + separateProcesses);
2453            }
2454        } else {
2455            mDefParseFlags = 0;
2456            mSeparateProcesses = null;
2457        }
2458
2459        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2460                "*dexopt*");
2461        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2462                installer, mInstallLock);
2463        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2464                dexManagerListener);
2465        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2466        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2467
2468        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2469                FgThread.get().getLooper());
2470
2471        getDefaultDisplayMetrics(context, mMetrics);
2472
2473        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2474        SystemConfig systemConfig = SystemConfig.getInstance();
2475        mAvailableFeatures = systemConfig.getAvailableFeatures();
2476        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2477
2478        mProtectedPackages = new ProtectedPackages(mContext);
2479
2480        synchronized (mInstallLock) {
2481        // writer
2482        synchronized (mPackages) {
2483            mHandlerThread = new ServiceThread(TAG,
2484                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2485            mHandlerThread.start();
2486            mHandler = new PackageHandler(mHandlerThread.getLooper());
2487            mProcessLoggingHandler = new ProcessLoggingHandler();
2488            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2489            mInstantAppRegistry = new InstantAppRegistry(this);
2490
2491            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2492            final int builtInLibCount = libConfig.size();
2493            for (int i = 0; i < builtInLibCount; i++) {
2494                String name = libConfig.keyAt(i);
2495                String path = libConfig.valueAt(i);
2496                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2497                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2498            }
2499
2500            SELinuxMMAC.readInstallPolicy();
2501
2502            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2503            FallbackCategoryProvider.loadFallbacks();
2504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2505
2506            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2507            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2508            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2509
2510            // Clean up orphaned packages for which the code path doesn't exist
2511            // and they are an update to a system app - caused by bug/32321269
2512            final int packageSettingCount = mSettings.mPackages.size();
2513            for (int i = packageSettingCount - 1; i >= 0; i--) {
2514                PackageSetting ps = mSettings.mPackages.valueAt(i);
2515                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2516                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2517                    mSettings.mPackages.removeAt(i);
2518                    mSettings.enableSystemPackageLPw(ps.name);
2519                }
2520            }
2521
2522            if (mFirstBoot) {
2523                requestCopyPreoptedFiles();
2524            }
2525
2526            String customResolverActivity = Resources.getSystem().getString(
2527                    R.string.config_customResolverActivity);
2528            if (TextUtils.isEmpty(customResolverActivity)) {
2529                customResolverActivity = null;
2530            } else {
2531                mCustomResolverComponentName = ComponentName.unflattenFromString(
2532                        customResolverActivity);
2533            }
2534
2535            long startTime = SystemClock.uptimeMillis();
2536
2537            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2538                    startTime);
2539
2540            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2541            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2542
2543            if (bootClassPath == null) {
2544                Slog.w(TAG, "No BOOTCLASSPATH found!");
2545            }
2546
2547            if (systemServerClassPath == null) {
2548                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2549            }
2550
2551            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2552
2553            final VersionInfo ver = mSettings.getInternalVersion();
2554            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2555            if (mIsUpgrade) {
2556                logCriticalInfo(Log.INFO,
2557                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2558            }
2559
2560            // when upgrading from pre-M, promote system app permissions from install to runtime
2561            mPromoteSystemApps =
2562                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2563
2564            // When upgrading from pre-N, we need to handle package extraction like first boot,
2565            // as there is no profiling data available.
2566            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2567
2568            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2569
2570            // save off the names of pre-existing system packages prior to scanning; we don't
2571            // want to automatically grant runtime permissions for new system apps
2572            if (mPromoteSystemApps) {
2573                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2574                while (pkgSettingIter.hasNext()) {
2575                    PackageSetting ps = pkgSettingIter.next();
2576                    if (isSystemApp(ps)) {
2577                        mExistingSystemPackages.add(ps.name);
2578                    }
2579                }
2580            }
2581
2582            mCacheDir = preparePackageParserCache(mIsUpgrade);
2583
2584            // Set flag to monitor and not change apk file paths when
2585            // scanning install directories.
2586            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2587
2588            if (mIsUpgrade || mFirstBoot) {
2589                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2590            }
2591
2592            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2593            // For security and version matching reason, only consider
2594            // overlay packages if they reside in the right directory.
2595            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2596                    mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2598                    scanFlags
2599                    | SCAN_AS_SYSTEM
2600                    | SCAN_AS_VENDOR,
2601                    0);
2602            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2603                    mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2605                    scanFlags
2606                    | SCAN_AS_SYSTEM
2607                    | SCAN_AS_PRODUCT,
2608                    0);
2609
2610            mParallelPackageParserCallback.findStaticOverlayPackages();
2611
2612            // Find base frameworks (resource packages without code).
2613            scanDirTracedLI(frameworkDir,
2614                    mDefParseFlags
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2616                    scanFlags
2617                    | SCAN_NO_DEX
2618                    | SCAN_AS_SYSTEM
2619                    | SCAN_AS_PRIVILEGED,
2620                    0);
2621
2622            // Collect privileged system packages.
2623            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2624            scanDirTracedLI(privilegedAppDir,
2625                    mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2627                    scanFlags
2628                    | SCAN_AS_SYSTEM
2629                    | SCAN_AS_PRIVILEGED,
2630                    0);
2631
2632            // Collect ordinary system packages.
2633            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2634            scanDirTracedLI(systemAppDir,
2635                    mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2637                    scanFlags
2638                    | SCAN_AS_SYSTEM,
2639                    0);
2640
2641            // Collect privileged vendor packages.
2642            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2643            try {
2644                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2645            } catch (IOException e) {
2646                // failed to look up canonical path, continue with original one
2647            }
2648            scanDirTracedLI(privilegedVendorAppDir,
2649                    mDefParseFlags
2650                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2651                    scanFlags
2652                    | SCAN_AS_SYSTEM
2653                    | SCAN_AS_VENDOR
2654                    | SCAN_AS_PRIVILEGED,
2655                    0);
2656
2657            // Collect ordinary vendor packages.
2658            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2659            try {
2660                vendorAppDir = vendorAppDir.getCanonicalFile();
2661            } catch (IOException e) {
2662                // failed to look up canonical path, continue with original one
2663            }
2664            scanDirTracedLI(vendorAppDir,
2665                    mDefParseFlags
2666                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2667                    scanFlags
2668                    | SCAN_AS_SYSTEM
2669                    | SCAN_AS_VENDOR,
2670                    0);
2671
2672            // Collect privileged odm packages. /odm is another vendor partition
2673            // other than /vendor.
2674            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2675                        "priv-app");
2676            try {
2677                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2678            } catch (IOException e) {
2679                // failed to look up canonical path, continue with original one
2680            }
2681            scanDirTracedLI(privilegedOdmAppDir,
2682                    mDefParseFlags
2683                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2684                    scanFlags
2685                    | SCAN_AS_SYSTEM
2686                    | SCAN_AS_VENDOR
2687                    | SCAN_AS_PRIVILEGED,
2688                    0);
2689
2690            // Collect ordinary odm packages. /odm is another vendor partition
2691            // other than /vendor.
2692            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2693            try {
2694                odmAppDir = odmAppDir.getCanonicalFile();
2695            } catch (IOException e) {
2696                // failed to look up canonical path, continue with original one
2697            }
2698            scanDirTracedLI(odmAppDir,
2699                    mDefParseFlags
2700                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2701                    scanFlags
2702                    | SCAN_AS_SYSTEM
2703                    | SCAN_AS_VENDOR,
2704                    0);
2705
2706            // Collect all OEM packages.
2707            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2708            scanDirTracedLI(oemAppDir,
2709                    mDefParseFlags
2710                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2711                    scanFlags
2712                    | SCAN_AS_SYSTEM
2713                    | SCAN_AS_OEM,
2714                    0);
2715
2716            // Collected privileged product packages.
2717            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2718            try {
2719                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2720            } catch (IOException e) {
2721                // failed to look up canonical path, continue with original one
2722            }
2723            scanDirTracedLI(privilegedProductAppDir,
2724                    mDefParseFlags
2725                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2726                    scanFlags
2727                    | SCAN_AS_SYSTEM
2728                    | SCAN_AS_PRODUCT
2729                    | SCAN_AS_PRIVILEGED,
2730                    0);
2731
2732            // Collect ordinary product packages.
2733            File productAppDir = new File(Environment.getProductDirectory(), "app");
2734            try {
2735                productAppDir = productAppDir.getCanonicalFile();
2736            } catch (IOException e) {
2737                // failed to look up canonical path, continue with original one
2738            }
2739            scanDirTracedLI(productAppDir,
2740                    mDefParseFlags
2741                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2742                    scanFlags
2743                    | SCAN_AS_SYSTEM
2744                    | SCAN_AS_PRODUCT,
2745                    0);
2746
2747            // Prune any system packages that no longer exist.
2748            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2749            // Stub packages must either be replaced with full versions in the /data
2750            // partition or be disabled.
2751            final List<String> stubSystemApps = new ArrayList<>();
2752            if (!mOnlyCore) {
2753                // do this first before mucking with mPackages for the "expecting better" case
2754                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2755                while (pkgIterator.hasNext()) {
2756                    final PackageParser.Package pkg = pkgIterator.next();
2757                    if (pkg.isStub) {
2758                        stubSystemApps.add(pkg.packageName);
2759                    }
2760                }
2761
2762                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2763                while (psit.hasNext()) {
2764                    PackageSetting ps = psit.next();
2765
2766                    /*
2767                     * If this is not a system app, it can't be a
2768                     * disable system app.
2769                     */
2770                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2771                        continue;
2772                    }
2773
2774                    /*
2775                     * If the package is scanned, it's not erased.
2776                     */
2777                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2778                    if (scannedPkg != null) {
2779                        /*
2780                         * If the system app is both scanned and in the
2781                         * disabled packages list, then it must have been
2782                         * added via OTA. Remove it from the currently
2783                         * scanned package so the previously user-installed
2784                         * application can be scanned.
2785                         */
2786                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2787                            logCriticalInfo(Log.WARN,
2788                                    "Expecting better updated system app for " + ps.name
2789                                    + "; removing system app.  Last known"
2790                                    + " codePath=" + ps.codePathString
2791                                    + ", versionCode=" + ps.versionCode
2792                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2793                            removePackageLI(scannedPkg, true);
2794                            mExpectingBetter.put(ps.name, ps.codePath);
2795                        }
2796
2797                        continue;
2798                    }
2799
2800                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2801                        psit.remove();
2802                        logCriticalInfo(Log.WARN, "System package " + ps.name
2803                                + " no longer exists; it's data will be wiped");
2804                        // Actual deletion of code and data will be handled by later
2805                        // reconciliation step
2806                    } else {
2807                        // we still have a disabled system package, but, it still might have
2808                        // been removed. check the code path still exists and check there's
2809                        // still a package. the latter can happen if an OTA keeps the same
2810                        // code path, but, changes the package name.
2811                        final PackageSetting disabledPs =
2812                                mSettings.getDisabledSystemPkgLPr(ps.name);
2813                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2814                                || disabledPs.pkg == null) {
2815                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2816                        }
2817                    }
2818                }
2819            }
2820
2821            //delete tmp files
2822            deleteTempPackageFiles();
2823
2824            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2825
2826            // Remove any shared userIDs that have no associated packages
2827            mSettings.pruneSharedUsersLPw();
2828            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2829            final int systemPackagesCount = mPackages.size();
2830            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2831                    + " ms, packageCount: " + systemPackagesCount
2832                    + " , timePerPackage: "
2833                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2834                    + " , cached: " + cachedSystemApps);
2835            if (mIsUpgrade && systemPackagesCount > 0) {
2836                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2837                        ((int) systemScanTime) / systemPackagesCount);
2838            }
2839            if (!mOnlyCore) {
2840                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2841                        SystemClock.uptimeMillis());
2842                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2843
2844                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2845                        | PackageParser.PARSE_FORWARD_LOCK,
2846                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2847
2848                // Remove disable package settings for updated system apps that were
2849                // removed via an OTA. If the update is no longer present, remove the
2850                // app completely. Otherwise, revoke their system privileges.
2851                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2852                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2853                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2854                    final String msg;
2855                    if (deletedPkg == null) {
2856                        // should have found an update, but, we didn't; remove everything
2857                        msg = "Updated system package " + deletedAppName
2858                                + " no longer exists; removing its data";
2859                        // Actual deletion of code and data will be handled by later
2860                        // reconciliation step
2861                    } else {
2862                        // found an update; revoke system privileges
2863                        msg = "Updated system package + " + deletedAppName
2864                                + " no longer exists; revoking system privileges";
2865
2866                        // Don't do anything if a stub is removed from the system image. If
2867                        // we were to remove the uncompressed version from the /data partition,
2868                        // this is where it'd be done.
2869
2870                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2871                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2872                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2873                    }
2874                    logCriticalInfo(Log.WARN, msg);
2875                }
2876
2877                /*
2878                 * Make sure all system apps that we expected to appear on
2879                 * the userdata partition actually showed up. If they never
2880                 * appeared, crawl back and revive the system version.
2881                 */
2882                for (int i = 0; i < mExpectingBetter.size(); i++) {
2883                    final String packageName = mExpectingBetter.keyAt(i);
2884                    if (!mPackages.containsKey(packageName)) {
2885                        final File scanFile = mExpectingBetter.valueAt(i);
2886
2887                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2888                                + " but never showed up; reverting to system");
2889
2890                        final @ParseFlags int reparseFlags;
2891                        final @ScanFlags int rescanFlags;
2892                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2893                            reparseFlags =
2894                                    mDefParseFlags |
2895                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2896                            rescanFlags =
2897                                    scanFlags
2898                                    | SCAN_AS_SYSTEM
2899                                    | SCAN_AS_PRIVILEGED;
2900                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2901                            reparseFlags =
2902                                    mDefParseFlags |
2903                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2904                            rescanFlags =
2905                                    scanFlags
2906                                    | SCAN_AS_SYSTEM;
2907                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2908                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2909                            reparseFlags =
2910                                    mDefParseFlags |
2911                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2912                            rescanFlags =
2913                                    scanFlags
2914                                    | SCAN_AS_SYSTEM
2915                                    | SCAN_AS_VENDOR
2916                                    | SCAN_AS_PRIVILEGED;
2917                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2918                                || FileUtils.contains(odmAppDir, scanFile)) {
2919                            reparseFlags =
2920                                    mDefParseFlags |
2921                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2922                            rescanFlags =
2923                                    scanFlags
2924                                    | SCAN_AS_SYSTEM
2925                                    | SCAN_AS_VENDOR;
2926                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2927                            reparseFlags =
2928                                    mDefParseFlags |
2929                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2930                            rescanFlags =
2931                                    scanFlags
2932                                    | SCAN_AS_SYSTEM
2933                                    | SCAN_AS_OEM;
2934                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2935                            reparseFlags =
2936                                    mDefParseFlags |
2937                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2938                            rescanFlags =
2939                                    scanFlags
2940                                    | SCAN_AS_SYSTEM
2941                                    | SCAN_AS_PRODUCT
2942                                    | SCAN_AS_PRIVILEGED;
2943                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2944                            reparseFlags =
2945                                    mDefParseFlags |
2946                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2947                            rescanFlags =
2948                                    scanFlags
2949                                    | SCAN_AS_SYSTEM
2950                                    | SCAN_AS_PRODUCT;
2951                        } else {
2952                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2953                            continue;
2954                        }
2955
2956                        mSettings.enableSystemPackageLPw(packageName);
2957
2958                        try {
2959                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2960                        } catch (PackageManagerException e) {
2961                            Slog.e(TAG, "Failed to parse original system package: "
2962                                    + e.getMessage());
2963                        }
2964                    }
2965                }
2966
2967                // Uncompress and install any stubbed system applications.
2968                // This must be done last to ensure all stubs are replaced or disabled.
2969                decompressSystemApplications(stubSystemApps, scanFlags);
2970
2971                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2972                                - cachedSystemApps;
2973
2974                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2975                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2976                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2977                        + " ms, packageCount: " + dataPackagesCount
2978                        + " , timePerPackage: "
2979                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2980                        + " , cached: " + cachedNonSystemApps);
2981                if (mIsUpgrade && dataPackagesCount > 0) {
2982                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2983                            ((int) dataScanTime) / dataPackagesCount);
2984                }
2985            }
2986            mExpectingBetter.clear();
2987
2988            // Resolve the storage manager.
2989            mStorageManagerPackage = getStorageManagerPackageName();
2990
2991            // Resolve protected action filters. Only the setup wizard is allowed to
2992            // have a high priority filter for these actions.
2993            mSetupWizardPackage = getSetupWizardPackageName();
2994            if (mProtectedFilters.size() > 0) {
2995                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2996                    Slog.i(TAG, "No setup wizard;"
2997                        + " All protected intents capped to priority 0");
2998                }
2999                for (ActivityIntentInfo filter : mProtectedFilters) {
3000                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
3001                        if (DEBUG_FILTERS) {
3002                            Slog.i(TAG, "Found setup wizard;"
3003                                + " allow priority " + filter.getPriority() + ";"
3004                                + " package: " + filter.activity.info.packageName
3005                                + " activity: " + filter.activity.className
3006                                + " priority: " + filter.getPriority());
3007                        }
3008                        // skip setup wizard; allow it to keep the high priority filter
3009                        continue;
3010                    }
3011                    if (DEBUG_FILTERS) {
3012                        Slog.i(TAG, "Protected action; cap priority to 0;"
3013                                + " package: " + filter.activity.info.packageName
3014                                + " activity: " + filter.activity.className
3015                                + " origPrio: " + filter.getPriority());
3016                    }
3017                    filter.setPriority(0);
3018                }
3019            }
3020
3021            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3022
3023            mDeferProtectedFilters = false;
3024            mProtectedFilters.clear();
3025
3026            // Now that we know all of the shared libraries, update all clients to have
3027            // the correct library paths.
3028            updateAllSharedLibrariesLPw(null);
3029
3030            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3031                // NOTE: We ignore potential failures here during a system scan (like
3032                // the rest of the commands above) because there's precious little we
3033                // can do about it. A settings error is reported, though.
3034                final List<String> changedAbiCodePath =
3035                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3036                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3037                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3038                        final String codePathString = changedAbiCodePath.get(i);
3039                        try {
3040                            mInstaller.rmdex(codePathString,
3041                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3042                        } catch (InstallerException ignored) {
3043                        }
3044                    }
3045                }
3046                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3047                // SELinux domain.
3048                setting.fixSeInfoLocked();
3049            }
3050
3051            // Now that we know all the packages we are keeping,
3052            // read and update their last usage times.
3053            mPackageUsage.read(mPackages);
3054            mCompilerStats.read();
3055
3056            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3057                    SystemClock.uptimeMillis());
3058            Slog.i(TAG, "Time to scan packages: "
3059                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3060                    + " seconds");
3061
3062            // If the platform SDK has changed since the last time we booted,
3063            // we need to re-grant app permission to catch any new ones that
3064            // appear.  This is really a hack, and means that apps can in some
3065            // cases get permissions that the user didn't initially explicitly
3066            // allow...  it would be nice to have some better way to handle
3067            // this situation.
3068            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3069            if (sdkUpdated) {
3070                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3071                        + mSdkVersion + "; regranting permissions for internal storage");
3072            }
3073            mPermissionManager.updateAllPermissions(
3074                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3075                    mPermissionCallback);
3076            ver.sdkVersion = mSdkVersion;
3077
3078            // If this is the first boot or an update from pre-M, and it is a normal
3079            // boot, then we need to initialize the default preferred apps across
3080            // all defined users.
3081            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3082                for (UserInfo user : sUserManager.getUsers(true)) {
3083                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3084                    applyFactoryDefaultBrowserLPw(user.id);
3085                    primeDomainVerificationsLPw(user.id);
3086                }
3087            }
3088
3089            // Prepare storage for system user really early during boot,
3090            // since core system apps like SettingsProvider and SystemUI
3091            // can't wait for user to start
3092            final int storageFlags;
3093            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3094                storageFlags = StorageManager.FLAG_STORAGE_DE;
3095            } else {
3096                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3097            }
3098            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3099                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3100                    true /* onlyCoreApps */);
3101            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3102                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3103                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3104                traceLog.traceBegin("AppDataFixup");
3105                try {
3106                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3107                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3108                } catch (InstallerException e) {
3109                    Slog.w(TAG, "Trouble fixing GIDs", e);
3110                }
3111                traceLog.traceEnd();
3112
3113                traceLog.traceBegin("AppDataPrepare");
3114                if (deferPackages == null || deferPackages.isEmpty()) {
3115                    return;
3116                }
3117                int count = 0;
3118                for (String pkgName : deferPackages) {
3119                    PackageParser.Package pkg = null;
3120                    synchronized (mPackages) {
3121                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3122                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3123                            pkg = ps.pkg;
3124                        }
3125                    }
3126                    if (pkg != null) {
3127                        synchronized (mInstallLock) {
3128                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3129                                    true /* maybeMigrateAppData */);
3130                        }
3131                        count++;
3132                    }
3133                }
3134                traceLog.traceEnd();
3135                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3136            }, "prepareAppData");
3137
3138            // If this is first boot after an OTA, and a normal boot, then
3139            // we need to clear code cache directories.
3140            // Note that we do *not* clear the application profiles. These remain valid
3141            // across OTAs and are used to drive profile verification (post OTA) and
3142            // profile compilation (without waiting to collect a fresh set of profiles).
3143            if (mIsUpgrade && !onlyCore) {
3144                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3145                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3146                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3147                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3148                        // No apps are running this early, so no need to freeze
3149                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3150                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3151                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3152                    }
3153                }
3154                ver.fingerprint = Build.FINGERPRINT;
3155            }
3156
3157            checkDefaultBrowser();
3158
3159            // clear only after permissions and other defaults have been updated
3160            mExistingSystemPackages.clear();
3161            mPromoteSystemApps = false;
3162
3163            // All the changes are done during package scanning.
3164            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3165
3166            // can downgrade to reader
3167            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3168            mSettings.writeLPr();
3169            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3170            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3171                    SystemClock.uptimeMillis());
3172
3173            if (!mOnlyCore) {
3174                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3175                mRequiredInstallerPackage = getRequiredInstallerLPr();
3176                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3177                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3178                if (mIntentFilterVerifierComponent != null) {
3179                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3180                            mIntentFilterVerifierComponent);
3181                } else {
3182                    mIntentFilterVerifier = null;
3183                }
3184                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3185                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3186                        SharedLibraryInfo.VERSION_UNDEFINED);
3187                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3188                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3189                        SharedLibraryInfo.VERSION_UNDEFINED);
3190            } else {
3191                mRequiredVerifierPackage = null;
3192                mRequiredInstallerPackage = null;
3193                mRequiredUninstallerPackage = null;
3194                mIntentFilterVerifierComponent = null;
3195                mIntentFilterVerifier = null;
3196                mServicesSystemSharedLibraryPackageName = null;
3197                mSharedSystemSharedLibraryPackageName = null;
3198            }
3199
3200            mInstallerService = new PackageInstallerService(context, this);
3201            final Pair<ComponentName, String> instantAppResolverComponent =
3202                    getInstantAppResolverLPr();
3203            if (instantAppResolverComponent != null) {
3204                if (DEBUG_INSTANT) {
3205                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3206                }
3207                mInstantAppResolverConnection = new InstantAppResolverConnection(
3208                        mContext, instantAppResolverComponent.first,
3209                        instantAppResolverComponent.second);
3210                mInstantAppResolverSettingsComponent =
3211                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3212            } else {
3213                mInstantAppResolverConnection = null;
3214                mInstantAppResolverSettingsComponent = null;
3215            }
3216            updateInstantAppInstallerLocked(null);
3217
3218            // Read and update the usage of dex files.
3219            // Do this at the end of PM init so that all the packages have their
3220            // data directory reconciled.
3221            // At this point we know the code paths of the packages, so we can validate
3222            // the disk file and build the internal cache.
3223            // The usage file is expected to be small so loading and verifying it
3224            // should take a fairly small time compare to the other activities (e.g. package
3225            // scanning).
3226            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3227            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3228            for (int userId : currentUserIds) {
3229                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3230            }
3231            mDexManager.load(userPackages);
3232            if (mIsUpgrade) {
3233                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3234                        (int) (SystemClock.uptimeMillis() - startTime));
3235            }
3236        } // synchronized (mPackages)
3237        } // synchronized (mInstallLock)
3238
3239        // Now after opening every single application zip, make sure they
3240        // are all flushed.  Not really needed, but keeps things nice and
3241        // tidy.
3242        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3243        Runtime.getRuntime().gc();
3244        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3245
3246        // The initial scanning above does many calls into installd while
3247        // holding the mPackages lock, but we're mostly interested in yelling
3248        // once we have a booted system.
3249        mInstaller.setWarnIfHeld(mPackages);
3250
3251        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3252    }
3253
3254    /**
3255     * Uncompress and install stub applications.
3256     * <p>In order to save space on the system partition, some applications are shipped in a
3257     * compressed form. In addition the compressed bits for the full application, the
3258     * system image contains a tiny stub comprised of only the Android manifest.
3259     * <p>During the first boot, attempt to uncompress and install the full application. If
3260     * the application can't be installed for any reason, disable the stub and prevent
3261     * uncompressing the full application during future boots.
3262     * <p>In order to forcefully attempt an installation of a full application, go to app
3263     * settings and enable the application.
3264     */
3265    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3266        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3267            final String pkgName = stubSystemApps.get(i);
3268            // skip if the system package is already disabled
3269            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3270                stubSystemApps.remove(i);
3271                continue;
3272            }
3273            // skip if the package isn't installed (?!); this should never happen
3274            final PackageParser.Package pkg = mPackages.get(pkgName);
3275            if (pkg == null) {
3276                stubSystemApps.remove(i);
3277                continue;
3278            }
3279            // skip if the package has been disabled by the user
3280            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3281            if (ps != null) {
3282                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3283                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3284                    stubSystemApps.remove(i);
3285                    continue;
3286                }
3287            }
3288
3289            if (DEBUG_COMPRESSION) {
3290                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3291            }
3292
3293            // uncompress the binary to its eventual destination on /data
3294            final File scanFile = decompressPackage(pkg);
3295            if (scanFile == null) {
3296                continue;
3297            }
3298
3299            // install the package to replace the stub on /system
3300            try {
3301                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3302                removePackageLI(pkg, true /*chatty*/);
3303                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3304                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3305                        UserHandle.USER_SYSTEM, "android");
3306                stubSystemApps.remove(i);
3307                continue;
3308            } catch (PackageManagerException e) {
3309                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3310            }
3311
3312            // any failed attempt to install the package will be cleaned up later
3313        }
3314
3315        // disable any stub still left; these failed to install the full application
3316        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3317            final String pkgName = stubSystemApps.get(i);
3318            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3319            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3320                    UserHandle.USER_SYSTEM, "android");
3321            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3322        }
3323    }
3324
3325    /**
3326     * Decompresses the given package on the system image onto
3327     * the /data partition.
3328     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3329     */
3330    private File decompressPackage(PackageParser.Package pkg) {
3331        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3332        if (compressedFiles == null || compressedFiles.length == 0) {
3333            if (DEBUG_COMPRESSION) {
3334                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3335            }
3336            return null;
3337        }
3338        final File dstCodePath =
3339                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3340        int ret = PackageManager.INSTALL_SUCCEEDED;
3341        try {
3342            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3343            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3344            for (File srcFile : compressedFiles) {
3345                final String srcFileName = srcFile.getName();
3346                final String dstFileName = srcFileName.substring(
3347                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3348                final File dstFile = new File(dstCodePath, dstFileName);
3349                ret = decompressFile(srcFile, dstFile);
3350                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3351                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3352                            + "; pkg: " + pkg.packageName
3353                            + ", file: " + dstFileName);
3354                    break;
3355                }
3356            }
3357        } catch (ErrnoException e) {
3358            logCriticalInfo(Log.ERROR, "Failed to decompress"
3359                    + "; pkg: " + pkg.packageName
3360                    + ", err: " + e.errno);
3361        }
3362        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3363            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3364            NativeLibraryHelper.Handle handle = null;
3365            try {
3366                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3367                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3368                        null /*abiOverride*/);
3369            } catch (IOException e) {
3370                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3371                        + "; pkg: " + pkg.packageName);
3372                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3373            } finally {
3374                IoUtils.closeQuietly(handle);
3375            }
3376        }
3377        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3378            if (dstCodePath == null || !dstCodePath.exists()) {
3379                return null;
3380            }
3381            removeCodePathLI(dstCodePath);
3382            return null;
3383        }
3384
3385        return dstCodePath;
3386    }
3387
3388    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3389        // we're only interested in updating the installer appliction when 1) it's not
3390        // already set or 2) the modified package is the installer
3391        if (mInstantAppInstallerActivity != null
3392                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3393                        .equals(modifiedPackage)) {
3394            return;
3395        }
3396        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3397    }
3398
3399    private static File preparePackageParserCache(boolean isUpgrade) {
3400        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3401            return null;
3402        }
3403
3404        // Disable package parsing on eng builds to allow for faster incremental development.
3405        if (Build.IS_ENG) {
3406            return null;
3407        }
3408
3409        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3410            Slog.i(TAG, "Disabling package parser cache due to system property.");
3411            return null;
3412        }
3413
3414        // The base directory for the package parser cache lives under /data/system/.
3415        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3416                "package_cache");
3417        if (cacheBaseDir == null) {
3418            return null;
3419        }
3420
3421        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3422        // This also serves to "GC" unused entries when the package cache version changes (which
3423        // can only happen during upgrades).
3424        if (isUpgrade) {
3425            FileUtils.deleteContents(cacheBaseDir);
3426        }
3427
3428
3429        // Return the versioned package cache directory. This is something like
3430        // "/data/system/package_cache/1"
3431        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3432
3433        if (cacheDir == null) {
3434            // Something went wrong. Attempt to delete everything and return.
3435            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3436            FileUtils.deleteContentsAndDir(cacheBaseDir);
3437            return null;
3438        }
3439
3440        // The following is a workaround to aid development on non-numbered userdebug
3441        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3442        // the system partition is newer.
3443        //
3444        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3445        // that starts with "eng." to signify that this is an engineering build and not
3446        // destined for release.
3447        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3448            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3449
3450            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3451            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3452            // in general and should not be used for production changes. In this specific case,
3453            // we know that they will work.
3454            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3455            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3456                FileUtils.deleteContents(cacheBaseDir);
3457                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3458            }
3459        }
3460
3461        return cacheDir;
3462    }
3463
3464    @Override
3465    public boolean isFirstBoot() {
3466        // allow instant applications
3467        return mFirstBoot;
3468    }
3469
3470    @Override
3471    public boolean isOnlyCoreApps() {
3472        // allow instant applications
3473        return mOnlyCore;
3474    }
3475
3476    @Override
3477    public boolean isUpgrade() {
3478        // allow instant applications
3479        // The system property allows testing ota flow when upgraded to the same image.
3480        return mIsUpgrade || SystemProperties.getBoolean(
3481                "persist.pm.mock-upgrade", false /* default */);
3482    }
3483
3484    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3485        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3486
3487        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3488                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3489                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3490        if (matches.size() == 1) {
3491            return matches.get(0).getComponentInfo().packageName;
3492        } else if (matches.size() == 0) {
3493            Log.e(TAG, "There should probably be a verifier, but, none were found");
3494            return null;
3495        }
3496        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3497    }
3498
3499    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3500        synchronized (mPackages) {
3501            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3502            if (libraryEntry == null) {
3503                throw new IllegalStateException("Missing required shared library:" + name);
3504            }
3505            return libraryEntry.apk;
3506        }
3507    }
3508
3509    private @NonNull String getRequiredInstallerLPr() {
3510        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3511        intent.addCategory(Intent.CATEGORY_DEFAULT);
3512        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3513
3514        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3515                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3516                UserHandle.USER_SYSTEM);
3517        if (matches.size() == 1) {
3518            ResolveInfo resolveInfo = matches.get(0);
3519            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3520                throw new RuntimeException("The installer must be a privileged app");
3521            }
3522            return matches.get(0).getComponentInfo().packageName;
3523        } else {
3524            throw new RuntimeException("There must be exactly one installer; found " + matches);
3525        }
3526    }
3527
3528    private @NonNull String getRequiredUninstallerLPr() {
3529        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3530        intent.addCategory(Intent.CATEGORY_DEFAULT);
3531        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3532
3533        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3534                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3535                UserHandle.USER_SYSTEM);
3536        if (resolveInfo == null ||
3537                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3538            throw new RuntimeException("There must be exactly one uninstaller; found "
3539                    + resolveInfo);
3540        }
3541        return resolveInfo.getComponentInfo().packageName;
3542    }
3543
3544    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3545        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3546
3547        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3548                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3549                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3550        ResolveInfo best = null;
3551        final int N = matches.size();
3552        for (int i = 0; i < N; i++) {
3553            final ResolveInfo cur = matches.get(i);
3554            final String packageName = cur.getComponentInfo().packageName;
3555            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3556                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3557                continue;
3558            }
3559
3560            if (best == null || cur.priority > best.priority) {
3561                best = cur;
3562            }
3563        }
3564
3565        if (best != null) {
3566            return best.getComponentInfo().getComponentName();
3567        }
3568        Slog.w(TAG, "Intent filter verifier not found");
3569        return null;
3570    }
3571
3572    @Override
3573    public @Nullable ComponentName getInstantAppResolverComponent() {
3574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3575            return null;
3576        }
3577        synchronized (mPackages) {
3578            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3579            if (instantAppResolver == null) {
3580                return null;
3581            }
3582            return instantAppResolver.first;
3583        }
3584    }
3585
3586    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3587        final String[] packageArray =
3588                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3589        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3590            if (DEBUG_INSTANT) {
3591                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3592            }
3593            return null;
3594        }
3595
3596        final int callingUid = Binder.getCallingUid();
3597        final int resolveFlags =
3598                MATCH_DIRECT_BOOT_AWARE
3599                | MATCH_DIRECT_BOOT_UNAWARE
3600                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3601        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3602        final Intent resolverIntent = new Intent(actionName);
3603        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3604                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3605        final int N = resolvers.size();
3606        if (N == 0) {
3607            if (DEBUG_INSTANT) {
3608                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3609            }
3610            return null;
3611        }
3612
3613        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3614        for (int i = 0; i < N; i++) {
3615            final ResolveInfo info = resolvers.get(i);
3616
3617            if (info.serviceInfo == null) {
3618                continue;
3619            }
3620
3621            final String packageName = info.serviceInfo.packageName;
3622            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3623                if (DEBUG_INSTANT) {
3624                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3625                            + " pkg: " + packageName + ", info:" + info);
3626                }
3627                continue;
3628            }
3629
3630            if (DEBUG_INSTANT) {
3631                Slog.v(TAG, "Ephemeral resolver found;"
3632                        + " pkg: " + packageName + ", info:" + info);
3633            }
3634            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3635        }
3636        if (DEBUG_INSTANT) {
3637            Slog.v(TAG, "Ephemeral resolver NOT found");
3638        }
3639        return null;
3640    }
3641
3642    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3643        String[] orderedActions = Build.IS_ENG
3644                ? new String[]{
3645                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3646                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3647                : new String[]{
3648                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3649
3650        final int resolveFlags =
3651                MATCH_DIRECT_BOOT_AWARE
3652                        | MATCH_DIRECT_BOOT_UNAWARE
3653                        | Intent.FLAG_IGNORE_EPHEMERAL
3654                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3655        final Intent intent = new Intent();
3656        intent.addCategory(Intent.CATEGORY_DEFAULT);
3657        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3658        List<ResolveInfo> matches = null;
3659        for (String action : orderedActions) {
3660            intent.setAction(action);
3661            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3662                    resolveFlags, UserHandle.USER_SYSTEM);
3663            if (matches.isEmpty()) {
3664                if (DEBUG_INSTANT) {
3665                    Slog.d(TAG, "Instant App installer not found with " + action);
3666                }
3667            } else {
3668                break;
3669            }
3670        }
3671        Iterator<ResolveInfo> iter = matches.iterator();
3672        while (iter.hasNext()) {
3673            final ResolveInfo rInfo = iter.next();
3674            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3675            if (ps != null) {
3676                final PermissionsState permissionsState = ps.getPermissionsState();
3677                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3678                        || Build.IS_ENG) {
3679                    continue;
3680                }
3681            }
3682            iter.remove();
3683        }
3684        if (matches.size() == 0) {
3685            return null;
3686        } else if (matches.size() == 1) {
3687            return (ActivityInfo) matches.get(0).getComponentInfo();
3688        } else {
3689            throw new RuntimeException(
3690                    "There must be at most one ephemeral installer; found " + matches);
3691        }
3692    }
3693
3694    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3695            @NonNull ComponentName resolver) {
3696        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3697                .addCategory(Intent.CATEGORY_DEFAULT)
3698                .setPackage(resolver.getPackageName());
3699        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3700        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3701                UserHandle.USER_SYSTEM);
3702        if (matches.isEmpty()) {
3703            return null;
3704        }
3705        return matches.get(0).getComponentInfo().getComponentName();
3706    }
3707
3708    private void primeDomainVerificationsLPw(int userId) {
3709        if (DEBUG_DOMAIN_VERIFICATION) {
3710            Slog.d(TAG, "Priming domain verifications in user " + userId);
3711        }
3712
3713        SystemConfig systemConfig = SystemConfig.getInstance();
3714        ArraySet<String> packages = systemConfig.getLinkedApps();
3715
3716        for (String packageName : packages) {
3717            PackageParser.Package pkg = mPackages.get(packageName);
3718            if (pkg != null) {
3719                if (!pkg.isSystem()) {
3720                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3721                    continue;
3722                }
3723
3724                ArraySet<String> domains = null;
3725                for (PackageParser.Activity a : pkg.activities) {
3726                    for (ActivityIntentInfo filter : a.intents) {
3727                        if (hasValidDomains(filter)) {
3728                            if (domains == null) {
3729                                domains = new ArraySet<String>();
3730                            }
3731                            domains.addAll(filter.getHostsList());
3732                        }
3733                    }
3734                }
3735
3736                if (domains != null && domains.size() > 0) {
3737                    if (DEBUG_DOMAIN_VERIFICATION) {
3738                        Slog.v(TAG, "      + " + packageName);
3739                    }
3740                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3741                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3742                    // and then 'always' in the per-user state actually used for intent resolution.
3743                    final IntentFilterVerificationInfo ivi;
3744                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3745                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3746                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3747                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3748                } else {
3749                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3750                            + "' does not handle web links");
3751                }
3752            } else {
3753                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3754            }
3755        }
3756
3757        scheduleWritePackageRestrictionsLocked(userId);
3758        scheduleWriteSettingsLocked();
3759    }
3760
3761    private void applyFactoryDefaultBrowserLPw(int userId) {
3762        // The default browser app's package name is stored in a string resource,
3763        // with a product-specific overlay used for vendor customization.
3764        String browserPkg = mContext.getResources().getString(
3765                com.android.internal.R.string.default_browser);
3766        if (!TextUtils.isEmpty(browserPkg)) {
3767            // non-empty string => required to be a known package
3768            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3769            if (ps == null) {
3770                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3771                browserPkg = null;
3772            } else {
3773                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3774            }
3775        }
3776
3777        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3778        // default.  If there's more than one, just leave everything alone.
3779        if (browserPkg == null) {
3780            calculateDefaultBrowserLPw(userId);
3781        }
3782    }
3783
3784    private void calculateDefaultBrowserLPw(int userId) {
3785        List<String> allBrowsers = resolveAllBrowserApps(userId);
3786        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3787        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3788    }
3789
3790    private List<String> resolveAllBrowserApps(int userId) {
3791        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3792        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3793                PackageManager.MATCH_ALL, userId);
3794
3795        final int count = list.size();
3796        List<String> result = new ArrayList<String>(count);
3797        for (int i=0; i<count; i++) {
3798            ResolveInfo info = list.get(i);
3799            if (info.activityInfo == null
3800                    || !info.handleAllWebDataURI
3801                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3802                    || result.contains(info.activityInfo.packageName)) {
3803                continue;
3804            }
3805            result.add(info.activityInfo.packageName);
3806        }
3807
3808        return result;
3809    }
3810
3811    private boolean packageIsBrowser(String packageName, int userId) {
3812        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3813                PackageManager.MATCH_ALL, userId);
3814        final int N = list.size();
3815        for (int i = 0; i < N; i++) {
3816            ResolveInfo info = list.get(i);
3817            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3818                return true;
3819            }
3820        }
3821        return false;
3822    }
3823
3824    private void checkDefaultBrowser() {
3825        final int myUserId = UserHandle.myUserId();
3826        final String packageName = getDefaultBrowserPackageName(myUserId);
3827        if (packageName != null) {
3828            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3829            if (info == null) {
3830                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3831                synchronized (mPackages) {
3832                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3833                }
3834            }
3835        }
3836    }
3837
3838    @Override
3839    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3840            throws RemoteException {
3841        try {
3842            return super.onTransact(code, data, reply, flags);
3843        } catch (RuntimeException e) {
3844            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3845                Slog.wtf(TAG, "Package Manager Crash", e);
3846            }
3847            throw e;
3848        }
3849    }
3850
3851    static int[] appendInts(int[] cur, int[] add) {
3852        if (add == null) return cur;
3853        if (cur == null) return add;
3854        final int N = add.length;
3855        for (int i=0; i<N; i++) {
3856            cur = appendInt(cur, add[i]);
3857        }
3858        return cur;
3859    }
3860
3861    /**
3862     * Returns whether or not a full application can see an instant application.
3863     * <p>
3864     * Currently, there are three cases in which this can occur:
3865     * <ol>
3866     * <li>The calling application is a "special" process. Special processes
3867     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3868     * <li>The calling application has the permission
3869     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3870     * <li>The calling application is the default launcher on the
3871     *     system partition.</li>
3872     * </ol>
3873     */
3874    private boolean canViewInstantApps(int callingUid, int userId) {
3875        if (callingUid < Process.FIRST_APPLICATION_UID) {
3876            return true;
3877        }
3878        if (mContext.checkCallingOrSelfPermission(
3879                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3880            return true;
3881        }
3882        if (mContext.checkCallingOrSelfPermission(
3883                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3884            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3885            if (homeComponent != null
3886                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3887                return true;
3888            }
3889        }
3890        return false;
3891    }
3892
3893    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3894        if (!sUserManager.exists(userId)) return null;
3895        if (ps == null) {
3896            return null;
3897        }
3898        final int callingUid = Binder.getCallingUid();
3899        // Filter out ephemeral app metadata:
3900        //   * The system/shell/root can see metadata for any app
3901        //   * An installed app can see metadata for 1) other installed apps
3902        //     and 2) ephemeral apps that have explicitly interacted with it
3903        //   * Ephemeral apps can only see their own data and exposed installed apps
3904        //   * Holding a signature permission allows seeing instant apps
3905        if (filterAppAccessLPr(ps, callingUid, userId)) {
3906            return null;
3907        }
3908
3909        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3910                && ps.isSystem()) {
3911            flags |= MATCH_ANY_USER;
3912        }
3913
3914        final PackageUserState state = ps.readUserState(userId);
3915        PackageParser.Package p = ps.pkg;
3916        if (p != null) {
3917            final PermissionsState permissionsState = ps.getPermissionsState();
3918
3919            // Compute GIDs only if requested
3920            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3921                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3922            // Compute granted permissions only if package has requested permissions
3923            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3924                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3925
3926            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3927                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3928
3929            if (packageInfo == null) {
3930                return null;
3931            }
3932
3933            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3934                    resolveExternalPackageNameLPr(p);
3935
3936            return packageInfo;
3937        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3938            PackageInfo pi = new PackageInfo();
3939            pi.packageName = ps.name;
3940            pi.setLongVersionCode(ps.versionCode);
3941            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3942            pi.firstInstallTime = ps.firstInstallTime;
3943            pi.lastUpdateTime = ps.lastUpdateTime;
3944
3945            ApplicationInfo ai = new ApplicationInfo();
3946            ai.packageName = ps.name;
3947            ai.uid = UserHandle.getUid(userId, ps.appId);
3948            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3949            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3950            ai.setVersionCode(ps.versionCode);
3951            ai.flags = ps.pkgFlags;
3952            ai.privateFlags = ps.pkgPrivateFlags;
3953            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3954
3955            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3956                    + ps.name + "]. Provides a minimum info.");
3957            return pi;
3958        } else {
3959            return null;
3960        }
3961    }
3962
3963    @Override
3964    public void checkPackageStartable(String packageName, int userId) {
3965        final int callingUid = Binder.getCallingUid();
3966        if (getInstantAppPackageName(callingUid) != null) {
3967            throw new SecurityException("Instant applications don't have access to this method");
3968        }
3969        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3970        synchronized (mPackages) {
3971            final PackageSetting ps = mSettings.mPackages.get(packageName);
3972            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3973                throw new SecurityException("Package " + packageName + " was not found!");
3974            }
3975
3976            if (!ps.getInstalled(userId)) {
3977                throw new SecurityException(
3978                        "Package " + packageName + " was not installed for user " + userId + "!");
3979            }
3980
3981            if (mSafeMode && !ps.isSystem()) {
3982                throw new SecurityException("Package " + packageName + " not a system app!");
3983            }
3984
3985            if (mFrozenPackages.contains(packageName)) {
3986                throw new SecurityException("Package " + packageName + " is currently frozen!");
3987            }
3988
3989            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3990                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3991            }
3992        }
3993    }
3994
3995    @Override
3996    public boolean isPackageAvailable(String packageName, int userId) {
3997        if (!sUserManager.exists(userId)) return false;
3998        final int callingUid = Binder.getCallingUid();
3999        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4000                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4001        synchronized (mPackages) {
4002            PackageParser.Package p = mPackages.get(packageName);
4003            if (p != null) {
4004                final PackageSetting ps = (PackageSetting) p.mExtras;
4005                if (filterAppAccessLPr(ps, callingUid, userId)) {
4006                    return false;
4007                }
4008                if (ps != null) {
4009                    final PackageUserState state = ps.readUserState(userId);
4010                    if (state != null) {
4011                        return PackageParser.isAvailable(state);
4012                    }
4013                }
4014            }
4015        }
4016        return false;
4017    }
4018
4019    @Override
4020    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4021        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4022                flags, Binder.getCallingUid(), userId);
4023    }
4024
4025    @Override
4026    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4027            int flags, int userId) {
4028        return getPackageInfoInternal(versionedPackage.getPackageName(),
4029                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4030    }
4031
4032    /**
4033     * Important: The provided filterCallingUid is used exclusively to filter out packages
4034     * that can be seen based on user state. It's typically the original caller uid prior
4035     * to clearing. Because it can only be provided by trusted code, it's value can be
4036     * trusted and will be used as-is; unlike userId which will be validated by this method.
4037     */
4038    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4039            int flags, int filterCallingUid, int userId) {
4040        if (!sUserManager.exists(userId)) return null;
4041        flags = updateFlagsForPackage(flags, userId, packageName);
4042        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4043                false /* requireFullPermission */, false /* checkShell */, "get package info");
4044
4045        // reader
4046        synchronized (mPackages) {
4047            // Normalize package name to handle renamed packages and static libs
4048            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4049
4050            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4051            if (matchFactoryOnly) {
4052                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4053                if (ps != null) {
4054                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4055                        return null;
4056                    }
4057                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4058                        return null;
4059                    }
4060                    return generatePackageInfo(ps, flags, userId);
4061                }
4062            }
4063
4064            PackageParser.Package p = mPackages.get(packageName);
4065            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4066                return null;
4067            }
4068            if (DEBUG_PACKAGE_INFO)
4069                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4070            if (p != null) {
4071                final PackageSetting ps = (PackageSetting) p.mExtras;
4072                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4073                    return null;
4074                }
4075                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4076                    return null;
4077                }
4078                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4079            }
4080            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4081                final PackageSetting ps = mSettings.mPackages.get(packageName);
4082                if (ps == null) return null;
4083                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4084                    return null;
4085                }
4086                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4087                    return null;
4088                }
4089                return generatePackageInfo(ps, flags, userId);
4090            }
4091        }
4092        return null;
4093    }
4094
4095    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4096        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4097            return true;
4098        }
4099        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4100            return true;
4101        }
4102        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4103            return true;
4104        }
4105        return false;
4106    }
4107
4108    private boolean isComponentVisibleToInstantApp(
4109            @Nullable ComponentName component, @ComponentType int type) {
4110        if (type == TYPE_ACTIVITY) {
4111            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4112            if (activity == null) {
4113                return false;
4114            }
4115            final boolean visibleToInstantApp =
4116                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4117            final boolean explicitlyVisibleToInstantApp =
4118                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4119            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4120        } else if (type == TYPE_RECEIVER) {
4121            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4122            if (activity == null) {
4123                return false;
4124            }
4125            final boolean visibleToInstantApp =
4126                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4127            final boolean explicitlyVisibleToInstantApp =
4128                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4129            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4130        } else if (type == TYPE_SERVICE) {
4131            final PackageParser.Service service = mServices.mServices.get(component);
4132            return service != null
4133                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4134                    : false;
4135        } else if (type == TYPE_PROVIDER) {
4136            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4137            return provider != null
4138                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4139                    : false;
4140        } else if (type == TYPE_UNKNOWN) {
4141            return isComponentVisibleToInstantApp(component);
4142        }
4143        return false;
4144    }
4145
4146    /**
4147     * Returns whether or not access to the application should be filtered.
4148     * <p>
4149     * Access may be limited based upon whether the calling or target applications
4150     * are instant applications.
4151     *
4152     * @see #canAccessInstantApps(int)
4153     */
4154    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4155            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4156        // if we're in an isolated process, get the real calling UID
4157        if (Process.isIsolated(callingUid)) {
4158            callingUid = mIsolatedOwners.get(callingUid);
4159        }
4160        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4161        final boolean callerIsInstantApp = instantAppPkgName != null;
4162        if (ps == null) {
4163            if (callerIsInstantApp) {
4164                // pretend the application exists, but, needs to be filtered
4165                return true;
4166            }
4167            return false;
4168        }
4169        // if the target and caller are the same application, don't filter
4170        if (isCallerSameApp(ps.name, callingUid)) {
4171            return false;
4172        }
4173        if (callerIsInstantApp) {
4174            // both caller and target are both instant, but, different applications, filter
4175            if (ps.getInstantApp(userId)) {
4176                return true;
4177            }
4178            // request for a specific component; if it hasn't been explicitly exposed through
4179            // property or instrumentation target, filter
4180            if (component != null) {
4181                final PackageParser.Instrumentation instrumentation =
4182                        mInstrumentation.get(component);
4183                if (instrumentation != null
4184                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4185                    return false;
4186                }
4187                return !isComponentVisibleToInstantApp(component, componentType);
4188            }
4189            // request for application; if no components have been explicitly exposed, filter
4190            return !ps.pkg.visibleToInstantApps;
4191        }
4192        if (ps.getInstantApp(userId)) {
4193            // caller can see all components of all instant applications, don't filter
4194            if (canViewInstantApps(callingUid, userId)) {
4195                return false;
4196            }
4197            // request for a specific instant application component, filter
4198            if (component != null) {
4199                return true;
4200            }
4201            // request for an instant application; if the caller hasn't been granted access, filter
4202            return !mInstantAppRegistry.isInstantAccessGranted(
4203                    userId, UserHandle.getAppId(callingUid), ps.appId);
4204        }
4205        return false;
4206    }
4207
4208    /**
4209     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4210     */
4211    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4212        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4213    }
4214
4215    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4216            int flags) {
4217        // Callers can access only the libs they depend on, otherwise they need to explicitly
4218        // ask for the shared libraries given the caller is allowed to access all static libs.
4219        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4220            // System/shell/root get to see all static libs
4221            final int appId = UserHandle.getAppId(uid);
4222            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4223                    || appId == Process.ROOT_UID) {
4224                return false;
4225            }
4226        }
4227
4228        // No package means no static lib as it is always on internal storage
4229        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4230            return false;
4231        }
4232
4233        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4234                ps.pkg.staticSharedLibVersion);
4235        if (libEntry == null) {
4236            return false;
4237        }
4238
4239        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4240        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4241        if (uidPackageNames == null) {
4242            return true;
4243        }
4244
4245        for (String uidPackageName : uidPackageNames) {
4246            if (ps.name.equals(uidPackageName)) {
4247                return false;
4248            }
4249            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4250            if (uidPs != null) {
4251                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4252                        libEntry.info.getName());
4253                if (index < 0) {
4254                    continue;
4255                }
4256                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4257                    return false;
4258                }
4259            }
4260        }
4261        return true;
4262    }
4263
4264    @Override
4265    public String[] currentToCanonicalPackageNames(String[] names) {
4266        final int callingUid = Binder.getCallingUid();
4267        if (getInstantAppPackageName(callingUid) != null) {
4268            return names;
4269        }
4270        final String[] out = new String[names.length];
4271        // reader
4272        synchronized (mPackages) {
4273            final int callingUserId = UserHandle.getUserId(callingUid);
4274            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4275            for (int i=names.length-1; i>=0; i--) {
4276                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4277                boolean translateName = false;
4278                if (ps != null && ps.realName != null) {
4279                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4280                    translateName = !targetIsInstantApp
4281                            || canViewInstantApps
4282                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4283                                    UserHandle.getAppId(callingUid), ps.appId);
4284                }
4285                out[i] = translateName ? ps.realName : names[i];
4286            }
4287        }
4288        return out;
4289    }
4290
4291    @Override
4292    public String[] canonicalToCurrentPackageNames(String[] names) {
4293        final int callingUid = Binder.getCallingUid();
4294        if (getInstantAppPackageName(callingUid) != null) {
4295            return names;
4296        }
4297        final String[] out = new String[names.length];
4298        // reader
4299        synchronized (mPackages) {
4300            final int callingUserId = UserHandle.getUserId(callingUid);
4301            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4302            for (int i=names.length-1; i>=0; i--) {
4303                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4304                boolean translateName = false;
4305                if (cur != null) {
4306                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4307                    final boolean targetIsInstantApp =
4308                            ps != null && ps.getInstantApp(callingUserId);
4309                    translateName = !targetIsInstantApp
4310                            || canViewInstantApps
4311                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4312                                    UserHandle.getAppId(callingUid), ps.appId);
4313                }
4314                out[i] = translateName ? cur : names[i];
4315            }
4316        }
4317        return out;
4318    }
4319
4320    @Override
4321    public int getPackageUid(String packageName, int flags, int userId) {
4322        if (!sUserManager.exists(userId)) return -1;
4323        final int callingUid = Binder.getCallingUid();
4324        flags = updateFlagsForPackage(flags, userId, packageName);
4325        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4326                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4327
4328        // reader
4329        synchronized (mPackages) {
4330            final PackageParser.Package p = mPackages.get(packageName);
4331            if (p != null && p.isMatch(flags)) {
4332                PackageSetting ps = (PackageSetting) p.mExtras;
4333                if (filterAppAccessLPr(ps, callingUid, userId)) {
4334                    return -1;
4335                }
4336                return UserHandle.getUid(userId, p.applicationInfo.uid);
4337            }
4338            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4339                final PackageSetting ps = mSettings.mPackages.get(packageName);
4340                if (ps != null && ps.isMatch(flags)
4341                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4342                    return UserHandle.getUid(userId, ps.appId);
4343                }
4344            }
4345        }
4346
4347        return -1;
4348    }
4349
4350    @Override
4351    public int[] getPackageGids(String packageName, int flags, int userId) {
4352        if (!sUserManager.exists(userId)) return null;
4353        final int callingUid = Binder.getCallingUid();
4354        flags = updateFlagsForPackage(flags, userId, packageName);
4355        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4356                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4357
4358        // reader
4359        synchronized (mPackages) {
4360            final PackageParser.Package p = mPackages.get(packageName);
4361            if (p != null && p.isMatch(flags)) {
4362                PackageSetting ps = (PackageSetting) p.mExtras;
4363                if (filterAppAccessLPr(ps, callingUid, userId)) {
4364                    return null;
4365                }
4366                // TODO: Shouldn't this be checking for package installed state for userId and
4367                // return null?
4368                return ps.getPermissionsState().computeGids(userId);
4369            }
4370            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4371                final PackageSetting ps = mSettings.mPackages.get(packageName);
4372                if (ps != null && ps.isMatch(flags)
4373                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4374                    return ps.getPermissionsState().computeGids(userId);
4375                }
4376            }
4377        }
4378
4379        return null;
4380    }
4381
4382    @Override
4383    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4384        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4385    }
4386
4387    @Override
4388    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4389            int flags) {
4390        final List<PermissionInfo> permissionList =
4391                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4392        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4393    }
4394
4395    @Override
4396    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4397        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4398    }
4399
4400    @Override
4401    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4402        final List<PermissionGroupInfo> permissionList =
4403                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4404        return (permissionList == null)
4405                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4406    }
4407
4408    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4409            int filterCallingUid, int userId) {
4410        if (!sUserManager.exists(userId)) return null;
4411        PackageSetting ps = mSettings.mPackages.get(packageName);
4412        if (ps != null) {
4413            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4414                return null;
4415            }
4416            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4417                return null;
4418            }
4419            if (ps.pkg == null) {
4420                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4421                if (pInfo != null) {
4422                    return pInfo.applicationInfo;
4423                }
4424                return null;
4425            }
4426            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4427                    ps.readUserState(userId), userId);
4428            if (ai != null) {
4429                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4430            }
4431            return ai;
4432        }
4433        return null;
4434    }
4435
4436    @Override
4437    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4438        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4439    }
4440
4441    /**
4442     * Important: The provided filterCallingUid is used exclusively to filter out applications
4443     * that can be seen based on user state. It's typically the original caller uid prior
4444     * to clearing. Because it can only be provided by trusted code, it's value can be
4445     * trusted and will be used as-is; unlike userId which will be validated by this method.
4446     */
4447    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4448            int filterCallingUid, int userId) {
4449        if (!sUserManager.exists(userId)) return null;
4450        flags = updateFlagsForApplication(flags, userId, packageName);
4451        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4452                false /* requireFullPermission */, false /* checkShell */, "get application info");
4453
4454        // writer
4455        synchronized (mPackages) {
4456            // Normalize package name to handle renamed packages and static libs
4457            packageName = resolveInternalPackageNameLPr(packageName,
4458                    PackageManager.VERSION_CODE_HIGHEST);
4459
4460            PackageParser.Package p = mPackages.get(packageName);
4461            if (DEBUG_PACKAGE_INFO) Log.v(
4462                    TAG, "getApplicationInfo " + packageName
4463                    + ": " + p);
4464            if (p != null) {
4465                PackageSetting ps = mSettings.mPackages.get(packageName);
4466                if (ps == null) return null;
4467                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4468                    return null;
4469                }
4470                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4471                    return null;
4472                }
4473                // Note: isEnabledLP() does not apply here - always return info
4474                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4475                        p, flags, ps.readUserState(userId), userId);
4476                if (ai != null) {
4477                    ai.packageName = resolveExternalPackageNameLPr(p);
4478                }
4479                return ai;
4480            }
4481            if ("android".equals(packageName)||"system".equals(packageName)) {
4482                return mAndroidApplication;
4483            }
4484            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4485                // Already generates the external package name
4486                return generateApplicationInfoFromSettingsLPw(packageName,
4487                        flags, filterCallingUid, userId);
4488            }
4489        }
4490        return null;
4491    }
4492
4493    private String normalizePackageNameLPr(String packageName) {
4494        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4495        return normalizedPackageName != null ? normalizedPackageName : packageName;
4496    }
4497
4498    @Override
4499    public void deletePreloadsFileCache() {
4500        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4501            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4502        }
4503        File dir = Environment.getDataPreloadsFileCacheDirectory();
4504        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4505        FileUtils.deleteContents(dir);
4506    }
4507
4508    @Override
4509    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4510            final int storageFlags, final IPackageDataObserver observer) {
4511        mContext.enforceCallingOrSelfPermission(
4512                android.Manifest.permission.CLEAR_APP_CACHE, null);
4513        mHandler.post(() -> {
4514            boolean success = false;
4515            try {
4516                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4517                success = true;
4518            } catch (IOException e) {
4519                Slog.w(TAG, e);
4520            }
4521            if (observer != null) {
4522                try {
4523                    observer.onRemoveCompleted(null, success);
4524                } catch (RemoteException e) {
4525                    Slog.w(TAG, e);
4526                }
4527            }
4528        });
4529    }
4530
4531    @Override
4532    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4533            final int storageFlags, final IntentSender pi) {
4534        mContext.enforceCallingOrSelfPermission(
4535                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4536        mHandler.post(() -> {
4537            boolean success = false;
4538            try {
4539                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4540                success = true;
4541            } catch (IOException e) {
4542                Slog.w(TAG, e);
4543            }
4544            if (pi != null) {
4545                try {
4546                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4547                } catch (SendIntentException e) {
4548                    Slog.w(TAG, e);
4549                }
4550            }
4551        });
4552    }
4553
4554    /**
4555     * Blocking call to clear various types of cached data across the system
4556     * until the requested bytes are available.
4557     */
4558    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4559        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4560        final File file = storage.findPathForUuid(volumeUuid);
4561        if (file.getUsableSpace() >= bytes) return;
4562
4563        if (ENABLE_FREE_CACHE_V2) {
4564            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4565                    volumeUuid);
4566            final boolean aggressive = (storageFlags
4567                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4568            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4569
4570            // 1. Pre-flight to determine if we have any chance to succeed
4571            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4572            if (internalVolume && (aggressive || SystemProperties
4573                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4574                deletePreloadsFileCache();
4575                if (file.getUsableSpace() >= bytes) return;
4576            }
4577
4578            // 3. Consider parsed APK data (aggressive only)
4579            if (internalVolume && aggressive) {
4580                FileUtils.deleteContents(mCacheDir);
4581                if (file.getUsableSpace() >= bytes) return;
4582            }
4583
4584            // 4. Consider cached app data (above quotas)
4585            try {
4586                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4587                        Installer.FLAG_FREE_CACHE_V2);
4588            } catch (InstallerException ignored) {
4589            }
4590            if (file.getUsableSpace() >= bytes) return;
4591
4592            // 5. Consider shared libraries with refcount=0 and age>min cache period
4593            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4594                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4595                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4596                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4597                return;
4598            }
4599
4600            // 6. Consider dexopt output (aggressive only)
4601            // TODO: Implement
4602
4603            // 7. Consider installed instant apps unused longer than min cache period
4604            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4605                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4606                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4607                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4608                return;
4609            }
4610
4611            // 8. Consider cached app data (below quotas)
4612            try {
4613                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4614                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4615            } catch (InstallerException ignored) {
4616            }
4617            if (file.getUsableSpace() >= bytes) return;
4618
4619            // 9. Consider DropBox entries
4620            // TODO: Implement
4621
4622            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4623            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4624                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4625                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4626                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4627                return;
4628            }
4629        } else {
4630            try {
4631                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4632            } catch (InstallerException ignored) {
4633            }
4634            if (file.getUsableSpace() >= bytes) return;
4635        }
4636
4637        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4638    }
4639
4640    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4641            throws IOException {
4642        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4643        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4644
4645        List<VersionedPackage> packagesToDelete = null;
4646        final long now = System.currentTimeMillis();
4647
4648        synchronized (mPackages) {
4649            final int[] allUsers = sUserManager.getUserIds();
4650            final int libCount = mSharedLibraries.size();
4651            for (int i = 0; i < libCount; i++) {
4652                final LongSparseArray<SharedLibraryEntry> versionedLib
4653                        = mSharedLibraries.valueAt(i);
4654                if (versionedLib == null) {
4655                    continue;
4656                }
4657                final int versionCount = versionedLib.size();
4658                for (int j = 0; j < versionCount; j++) {
4659                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4660                    // Skip packages that are not static shared libs.
4661                    if (!libInfo.isStatic()) {
4662                        break;
4663                    }
4664                    // Important: We skip static shared libs used for some user since
4665                    // in such a case we need to keep the APK on the device. The check for
4666                    // a lib being used for any user is performed by the uninstall call.
4667                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4668                    // Resolve the package name - we use synthetic package names internally
4669                    final String internalPackageName = resolveInternalPackageNameLPr(
4670                            declaringPackage.getPackageName(),
4671                            declaringPackage.getLongVersionCode());
4672                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4673                    // Skip unused static shared libs cached less than the min period
4674                    // to prevent pruning a lib needed by a subsequently installed package.
4675                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4676                        continue;
4677                    }
4678                    if (packagesToDelete == null) {
4679                        packagesToDelete = new ArrayList<>();
4680                    }
4681                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4682                            declaringPackage.getLongVersionCode()));
4683                }
4684            }
4685        }
4686
4687        if (packagesToDelete != null) {
4688            final int packageCount = packagesToDelete.size();
4689            for (int i = 0; i < packageCount; i++) {
4690                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4691                // Delete the package synchronously (will fail of the lib used for any user).
4692                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4693                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4694                                == PackageManager.DELETE_SUCCEEDED) {
4695                    if (volume.getUsableSpace() >= neededSpace) {
4696                        return true;
4697                    }
4698                }
4699            }
4700        }
4701
4702        return false;
4703    }
4704
4705    /**
4706     * Update given flags based on encryption status of current user.
4707     */
4708    private int updateFlags(int flags, int userId) {
4709        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4710                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4711            // Caller expressed an explicit opinion about what encryption
4712            // aware/unaware components they want to see, so fall through and
4713            // give them what they want
4714        } else {
4715            // Caller expressed no opinion, so match based on user state
4716            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4717                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4718            } else {
4719                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4720            }
4721        }
4722        return flags;
4723    }
4724
4725    private UserManagerInternal getUserManagerInternal() {
4726        if (mUserManagerInternal == null) {
4727            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4728        }
4729        return mUserManagerInternal;
4730    }
4731
4732    private ActivityManagerInternal getActivityManagerInternal() {
4733        if (mActivityManagerInternal == null) {
4734            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4735        }
4736        return mActivityManagerInternal;
4737    }
4738
4739
4740    private DeviceIdleController.LocalService getDeviceIdleController() {
4741        if (mDeviceIdleController == null) {
4742            mDeviceIdleController =
4743                    LocalServices.getService(DeviceIdleController.LocalService.class);
4744        }
4745        return mDeviceIdleController;
4746    }
4747
4748    /**
4749     * Update given flags when being used to request {@link PackageInfo}.
4750     */
4751    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4752        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4753        boolean triaged = true;
4754        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4755                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4756            // Caller is asking for component details, so they'd better be
4757            // asking for specific encryption matching behavior, or be triaged
4758            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4759                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4760                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4761                triaged = false;
4762            }
4763        }
4764        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4765                | PackageManager.MATCH_SYSTEM_ONLY
4766                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4767            triaged = false;
4768        }
4769        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4770            mPermissionManager.enforceCrossUserPermission(
4771                    Binder.getCallingUid(), userId, false, false,
4772                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4773                    + Debug.getCallers(5));
4774        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4775                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4776            // If the caller wants all packages and has a restricted profile associated with it,
4777            // then match all users. This is to make sure that launchers that need to access work
4778            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4779            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4780            flags |= PackageManager.MATCH_ANY_USER;
4781        }
4782        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4783            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4784                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4785        }
4786        return updateFlags(flags, userId);
4787    }
4788
4789    /**
4790     * Update given flags when being used to request {@link ApplicationInfo}.
4791     */
4792    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4793        return updateFlagsForPackage(flags, userId, cookie);
4794    }
4795
4796    /**
4797     * Update given flags when being used to request {@link ComponentInfo}.
4798     */
4799    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4800        if (cookie instanceof Intent) {
4801            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4802                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4803            }
4804        }
4805
4806        boolean triaged = true;
4807        // Caller is asking for component details, so they'd better be
4808        // asking for specific encryption matching behavior, or be triaged
4809        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4810                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4811                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4812            triaged = false;
4813        }
4814        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4815            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4816                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4817        }
4818
4819        return updateFlags(flags, userId);
4820    }
4821
4822    /**
4823     * Update given intent when being used to request {@link ResolveInfo}.
4824     */
4825    private Intent updateIntentForResolve(Intent intent) {
4826        if (intent.getSelector() != null) {
4827            intent = intent.getSelector();
4828        }
4829        if (DEBUG_PREFERRED) {
4830            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4831        }
4832        return intent;
4833    }
4834
4835    /**
4836     * Update given flags when being used to request {@link ResolveInfo}.
4837     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4838     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4839     * flag set. However, this flag is only honoured in three circumstances:
4840     * <ul>
4841     * <li>when called from a system process</li>
4842     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4843     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4844     * action and a {@code android.intent.category.BROWSABLE} category</li>
4845     * </ul>
4846     */
4847    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4848        return updateFlagsForResolve(flags, userId, intent, callingUid,
4849                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4850    }
4851    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4852            boolean wantInstantApps) {
4853        return updateFlagsForResolve(flags, userId, intent, callingUid,
4854                wantInstantApps, false /*onlyExposedExplicitly*/);
4855    }
4856    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4857            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4858        // Safe mode means we shouldn't match any third-party components
4859        if (mSafeMode) {
4860            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4861        }
4862        if (getInstantAppPackageName(callingUid) != null) {
4863            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4864            if (onlyExposedExplicitly) {
4865                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4866            }
4867            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4868            flags |= PackageManager.MATCH_INSTANT;
4869        } else {
4870            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4871            final boolean allowMatchInstant = wantInstantApps
4872                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4873            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4874                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4875            if (!allowMatchInstant) {
4876                flags &= ~PackageManager.MATCH_INSTANT;
4877            }
4878        }
4879        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4880    }
4881
4882    @Override
4883    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4884        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4885    }
4886
4887    /**
4888     * Important: The provided filterCallingUid is used exclusively to filter out activities
4889     * that can be seen based on user state. It's typically the original caller uid prior
4890     * to clearing. Because it can only be provided by trusted code, it's value can be
4891     * trusted and will be used as-is; unlike userId which will be validated by this method.
4892     */
4893    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4894            int filterCallingUid, int userId) {
4895        if (!sUserManager.exists(userId)) return null;
4896        flags = updateFlagsForComponent(flags, userId, component);
4897
4898        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4899            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4900                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4901        }
4902
4903        synchronized (mPackages) {
4904            PackageParser.Activity a = mActivities.mActivities.get(component);
4905
4906            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4907            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4908                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4909                if (ps == null) return null;
4910                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4911                    return null;
4912                }
4913                return PackageParser.generateActivityInfo(
4914                        a, flags, ps.readUserState(userId), userId);
4915            }
4916            if (mResolveComponentName.equals(component)) {
4917                return PackageParser.generateActivityInfo(
4918                        mResolveActivity, flags, new PackageUserState(), userId);
4919            }
4920        }
4921        return null;
4922    }
4923
4924    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4925        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4926            return false;
4927        }
4928        final long token = Binder.clearCallingIdentity();
4929        try {
4930            final int callingUserId = UserHandle.getUserId(callingUid);
4931            if (ActivityManager.getCurrentUser() != callingUserId) {
4932                return false;
4933            }
4934            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4935        } finally {
4936            Binder.restoreCallingIdentity(token);
4937        }
4938    }
4939
4940    @Override
4941    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4942            String resolvedType) {
4943        synchronized (mPackages) {
4944            if (component.equals(mResolveComponentName)) {
4945                // The resolver supports EVERYTHING!
4946                return true;
4947            }
4948            final int callingUid = Binder.getCallingUid();
4949            final int callingUserId = UserHandle.getUserId(callingUid);
4950            PackageParser.Activity a = mActivities.mActivities.get(component);
4951            if (a == null) {
4952                return false;
4953            }
4954            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4955            if (ps == null) {
4956                return false;
4957            }
4958            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4959                return false;
4960            }
4961            for (int i=0; i<a.intents.size(); i++) {
4962                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4963                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4964                    return true;
4965                }
4966            }
4967            return false;
4968        }
4969    }
4970
4971    @Override
4972    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4973        if (!sUserManager.exists(userId)) return null;
4974        final int callingUid = Binder.getCallingUid();
4975        flags = updateFlagsForComponent(flags, userId, component);
4976        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4977                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4978        synchronized (mPackages) {
4979            PackageParser.Activity a = mReceivers.mActivities.get(component);
4980            if (DEBUG_PACKAGE_INFO) Log.v(
4981                TAG, "getReceiverInfo " + component + ": " + a);
4982            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4983                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4984                if (ps == null) return null;
4985                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4986                    return null;
4987                }
4988                return PackageParser.generateActivityInfo(
4989                        a, flags, ps.readUserState(userId), userId);
4990            }
4991        }
4992        return null;
4993    }
4994
4995    @Override
4996    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4997            int flags, int userId) {
4998        if (!sUserManager.exists(userId)) return null;
4999        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5000        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5001            return null;
5002        }
5003
5004        flags = updateFlagsForPackage(flags, userId, null);
5005
5006        final boolean canSeeStaticLibraries =
5007                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5008                        == PERMISSION_GRANTED
5009                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5010                        == PERMISSION_GRANTED
5011                || canRequestPackageInstallsInternal(packageName,
5012                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5013                        false  /* throwIfPermNotDeclared*/)
5014                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5015                        == PERMISSION_GRANTED;
5016
5017        synchronized (mPackages) {
5018            List<SharedLibraryInfo> result = null;
5019
5020            final int libCount = mSharedLibraries.size();
5021            for (int i = 0; i < libCount; i++) {
5022                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5023                if (versionedLib == null) {
5024                    continue;
5025                }
5026
5027                final int versionCount = versionedLib.size();
5028                for (int j = 0; j < versionCount; j++) {
5029                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5030                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5031                        break;
5032                    }
5033                    final long identity = Binder.clearCallingIdentity();
5034                    try {
5035                        PackageInfo packageInfo = getPackageInfoVersioned(
5036                                libInfo.getDeclaringPackage(), flags
5037                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5038                        if (packageInfo == null) {
5039                            continue;
5040                        }
5041                    } finally {
5042                        Binder.restoreCallingIdentity(identity);
5043                    }
5044
5045                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5046                            libInfo.getLongVersion(), libInfo.getType(),
5047                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5048                            flags, userId));
5049
5050                    if (result == null) {
5051                        result = new ArrayList<>();
5052                    }
5053                    result.add(resLibInfo);
5054                }
5055            }
5056
5057            return result != null ? new ParceledListSlice<>(result) : null;
5058        }
5059    }
5060
5061    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5062            SharedLibraryInfo libInfo, int flags, int userId) {
5063        List<VersionedPackage> versionedPackages = null;
5064        final int packageCount = mSettings.mPackages.size();
5065        for (int i = 0; i < packageCount; i++) {
5066            PackageSetting ps = mSettings.mPackages.valueAt(i);
5067
5068            if (ps == null) {
5069                continue;
5070            }
5071
5072            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5073                continue;
5074            }
5075
5076            final String libName = libInfo.getName();
5077            if (libInfo.isStatic()) {
5078                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5079                if (libIdx < 0) {
5080                    continue;
5081                }
5082                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5083                    continue;
5084                }
5085                if (versionedPackages == null) {
5086                    versionedPackages = new ArrayList<>();
5087                }
5088                // If the dependent is a static shared lib, use the public package name
5089                String dependentPackageName = ps.name;
5090                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5091                    dependentPackageName = ps.pkg.manifestPackageName;
5092                }
5093                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5094            } else if (ps.pkg != null) {
5095                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5096                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5097                    if (versionedPackages == null) {
5098                        versionedPackages = new ArrayList<>();
5099                    }
5100                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5101                }
5102            }
5103        }
5104
5105        return versionedPackages;
5106    }
5107
5108    @Override
5109    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5110        if (!sUserManager.exists(userId)) return null;
5111        final int callingUid = Binder.getCallingUid();
5112        flags = updateFlagsForComponent(flags, userId, component);
5113        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5114                false /* requireFullPermission */, false /* checkShell */, "get service info");
5115        synchronized (mPackages) {
5116            PackageParser.Service s = mServices.mServices.get(component);
5117            if (DEBUG_PACKAGE_INFO) Log.v(
5118                TAG, "getServiceInfo " + component + ": " + s);
5119            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5120                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5121                if (ps == null) return null;
5122                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5123                    return null;
5124                }
5125                return PackageParser.generateServiceInfo(
5126                        s, flags, ps.readUserState(userId), userId);
5127            }
5128        }
5129        return null;
5130    }
5131
5132    @Override
5133    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5134        if (!sUserManager.exists(userId)) return null;
5135        final int callingUid = Binder.getCallingUid();
5136        flags = updateFlagsForComponent(flags, userId, component);
5137        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5138                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5139        synchronized (mPackages) {
5140            PackageParser.Provider p = mProviders.mProviders.get(component);
5141            if (DEBUG_PACKAGE_INFO) Log.v(
5142                TAG, "getProviderInfo " + component + ": " + p);
5143            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5144                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5145                if (ps == null) return null;
5146                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5147                    return null;
5148                }
5149                return PackageParser.generateProviderInfo(
5150                        p, flags, ps.readUserState(userId), userId);
5151            }
5152        }
5153        return null;
5154    }
5155
5156    @Override
5157    public String[] getSystemSharedLibraryNames() {
5158        // allow instant applications
5159        synchronized (mPackages) {
5160            Set<String> libs = null;
5161            final int libCount = mSharedLibraries.size();
5162            for (int i = 0; i < libCount; i++) {
5163                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5164                if (versionedLib == null) {
5165                    continue;
5166                }
5167                final int versionCount = versionedLib.size();
5168                for (int j = 0; j < versionCount; j++) {
5169                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5170                    if (!libEntry.info.isStatic()) {
5171                        if (libs == null) {
5172                            libs = new ArraySet<>();
5173                        }
5174                        libs.add(libEntry.info.getName());
5175                        break;
5176                    }
5177                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5178                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5179                            UserHandle.getUserId(Binder.getCallingUid()),
5180                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5181                        if (libs == null) {
5182                            libs = new ArraySet<>();
5183                        }
5184                        libs.add(libEntry.info.getName());
5185                        break;
5186                    }
5187                }
5188            }
5189
5190            if (libs != null) {
5191                String[] libsArray = new String[libs.size()];
5192                libs.toArray(libsArray);
5193                return libsArray;
5194            }
5195
5196            return null;
5197        }
5198    }
5199
5200    @Override
5201    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5202        // allow instant applications
5203        synchronized (mPackages) {
5204            return mServicesSystemSharedLibraryPackageName;
5205        }
5206    }
5207
5208    @Override
5209    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5210        // allow instant applications
5211        synchronized (mPackages) {
5212            return mSharedSystemSharedLibraryPackageName;
5213        }
5214    }
5215
5216    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5217        for (int i = userList.length - 1; i >= 0; --i) {
5218            final int userId = userList[i];
5219            // don't add instant app to the list of updates
5220            if (pkgSetting.getInstantApp(userId)) {
5221                continue;
5222            }
5223            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5224            if (changedPackages == null) {
5225                changedPackages = new SparseArray<>();
5226                mChangedPackages.put(userId, changedPackages);
5227            }
5228            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5229            if (sequenceNumbers == null) {
5230                sequenceNumbers = new HashMap<>();
5231                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5232            }
5233            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5234            if (sequenceNumber != null) {
5235                changedPackages.remove(sequenceNumber);
5236            }
5237            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5238            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5239        }
5240        mChangedPackagesSequenceNumber++;
5241    }
5242
5243    @Override
5244    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5245        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5246            return null;
5247        }
5248        synchronized (mPackages) {
5249            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5250                return null;
5251            }
5252            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5253            if (changedPackages == null) {
5254                return null;
5255            }
5256            final List<String> packageNames =
5257                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5258            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5259                final String packageName = changedPackages.get(i);
5260                if (packageName != null) {
5261                    packageNames.add(packageName);
5262                }
5263            }
5264            return packageNames.isEmpty()
5265                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5266        }
5267    }
5268
5269    @Override
5270    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5271        // allow instant applications
5272        ArrayList<FeatureInfo> res;
5273        synchronized (mAvailableFeatures) {
5274            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5275            res.addAll(mAvailableFeatures.values());
5276        }
5277        final FeatureInfo fi = new FeatureInfo();
5278        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5279                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5280        res.add(fi);
5281
5282        return new ParceledListSlice<>(res);
5283    }
5284
5285    @Override
5286    public boolean hasSystemFeature(String name, int version) {
5287        // allow instant applications
5288        synchronized (mAvailableFeatures) {
5289            final FeatureInfo feat = mAvailableFeatures.get(name);
5290            if (feat == null) {
5291                return false;
5292            } else {
5293                return feat.version >= version;
5294            }
5295        }
5296    }
5297
5298    @Override
5299    public int checkPermission(String permName, String pkgName, int userId) {
5300        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5301    }
5302
5303    @Override
5304    public int checkUidPermission(String permName, int uid) {
5305        synchronized (mPackages) {
5306            final String[] packageNames = getPackagesForUid(uid);
5307            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5308                    ? mPackages.get(packageNames[0])
5309                    : null;
5310            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5311        }
5312    }
5313
5314    @Override
5315    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5316        if (UserHandle.getCallingUserId() != userId) {
5317            mContext.enforceCallingPermission(
5318                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5319                    "isPermissionRevokedByPolicy for user " + userId);
5320        }
5321
5322        if (checkPermission(permission, packageName, userId)
5323                == PackageManager.PERMISSION_GRANTED) {
5324            return false;
5325        }
5326
5327        final int callingUid = Binder.getCallingUid();
5328        if (getInstantAppPackageName(callingUid) != null) {
5329            if (!isCallerSameApp(packageName, callingUid)) {
5330                return false;
5331            }
5332        } else {
5333            if (isInstantApp(packageName, userId)) {
5334                return false;
5335            }
5336        }
5337
5338        final long identity = Binder.clearCallingIdentity();
5339        try {
5340            final int flags = getPermissionFlags(permission, packageName, userId);
5341            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5342        } finally {
5343            Binder.restoreCallingIdentity(identity);
5344        }
5345    }
5346
5347    @Override
5348    public String getPermissionControllerPackageName() {
5349        synchronized (mPackages) {
5350            return mRequiredInstallerPackage;
5351        }
5352    }
5353
5354    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5355        return mPermissionManager.addDynamicPermission(
5356                info, async, getCallingUid(), new PermissionCallback() {
5357                    @Override
5358                    public void onPermissionChanged() {
5359                        if (!async) {
5360                            mSettings.writeLPr();
5361                        } else {
5362                            scheduleWriteSettingsLocked();
5363                        }
5364                    }
5365                });
5366    }
5367
5368    @Override
5369    public boolean addPermission(PermissionInfo info) {
5370        synchronized (mPackages) {
5371            return addDynamicPermission(info, false);
5372        }
5373    }
5374
5375    @Override
5376    public boolean addPermissionAsync(PermissionInfo info) {
5377        synchronized (mPackages) {
5378            return addDynamicPermission(info, true);
5379        }
5380    }
5381
5382    @Override
5383    public void removePermission(String permName) {
5384        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5385    }
5386
5387    @Override
5388    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5389        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5390                getCallingUid(), userId, mPermissionCallback);
5391    }
5392
5393    @Override
5394    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5395        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5396                getCallingUid(), userId, mPermissionCallback);
5397    }
5398
5399    @Override
5400    public void resetRuntimePermissions() {
5401        mContext.enforceCallingOrSelfPermission(
5402                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5403                "revokeRuntimePermission");
5404
5405        int callingUid = Binder.getCallingUid();
5406        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5407            mContext.enforceCallingOrSelfPermission(
5408                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5409                    "resetRuntimePermissions");
5410        }
5411
5412        synchronized (mPackages) {
5413            mPermissionManager.updateAllPermissions(
5414                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5415                    mPermissionCallback);
5416            for (int userId : UserManagerService.getInstance().getUserIds()) {
5417                final int packageCount = mPackages.size();
5418                for (int i = 0; i < packageCount; i++) {
5419                    PackageParser.Package pkg = mPackages.valueAt(i);
5420                    if (!(pkg.mExtras instanceof PackageSetting)) {
5421                        continue;
5422                    }
5423                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5424                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5425                }
5426            }
5427        }
5428    }
5429
5430    @Override
5431    public int getPermissionFlags(String permName, String packageName, int userId) {
5432        return mPermissionManager.getPermissionFlags(
5433                permName, packageName, getCallingUid(), userId);
5434    }
5435
5436    @Override
5437    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5438            int flagValues, int userId) {
5439        mPermissionManager.updatePermissionFlags(
5440                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5441                mPermissionCallback);
5442    }
5443
5444    /**
5445     * Update the permission flags for all packages and runtime permissions of a user in order
5446     * to allow device or profile owner to remove POLICY_FIXED.
5447     */
5448    @Override
5449    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5450        synchronized (mPackages) {
5451            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5452                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5453                    mPermissionCallback);
5454            if (changed) {
5455                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5456            }
5457        }
5458    }
5459
5460    @Override
5461    public boolean shouldShowRequestPermissionRationale(String permissionName,
5462            String packageName, int userId) {
5463        if (UserHandle.getCallingUserId() != userId) {
5464            mContext.enforceCallingPermission(
5465                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5466                    "canShowRequestPermissionRationale for user " + userId);
5467        }
5468
5469        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5470        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5471            return false;
5472        }
5473
5474        if (checkPermission(permissionName, packageName, userId)
5475                == PackageManager.PERMISSION_GRANTED) {
5476            return false;
5477        }
5478
5479        final int flags;
5480
5481        final long identity = Binder.clearCallingIdentity();
5482        try {
5483            flags = getPermissionFlags(permissionName,
5484                    packageName, userId);
5485        } finally {
5486            Binder.restoreCallingIdentity(identity);
5487        }
5488
5489        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5490                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5491                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5492
5493        if ((flags & fixedFlags) != 0) {
5494            return false;
5495        }
5496
5497        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5498    }
5499
5500    @Override
5501    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5502        mContext.enforceCallingOrSelfPermission(
5503                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5504                "addOnPermissionsChangeListener");
5505
5506        synchronized (mPackages) {
5507            mOnPermissionChangeListeners.addListenerLocked(listener);
5508        }
5509    }
5510
5511    @Override
5512    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5514            throw new SecurityException("Instant applications don't have access to this method");
5515        }
5516        synchronized (mPackages) {
5517            mOnPermissionChangeListeners.removeListenerLocked(listener);
5518        }
5519    }
5520
5521    @Override
5522    public boolean isProtectedBroadcast(String actionName) {
5523        // allow instant applications
5524        synchronized (mProtectedBroadcasts) {
5525            if (mProtectedBroadcasts.contains(actionName)) {
5526                return true;
5527            } else if (actionName != null) {
5528                // TODO: remove these terrible hacks
5529                if (actionName.startsWith("android.net.netmon.lingerExpired")
5530                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5531                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5532                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5533                    return true;
5534                }
5535            }
5536        }
5537        return false;
5538    }
5539
5540    @Override
5541    public int checkSignatures(String pkg1, String pkg2) {
5542        synchronized (mPackages) {
5543            final PackageParser.Package p1 = mPackages.get(pkg1);
5544            final PackageParser.Package p2 = mPackages.get(pkg2);
5545            if (p1 == null || p1.mExtras == null
5546                    || p2 == null || p2.mExtras == null) {
5547                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5548            }
5549            final int callingUid = Binder.getCallingUid();
5550            final int callingUserId = UserHandle.getUserId(callingUid);
5551            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5552            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5553            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5554                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5555                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5556            }
5557            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5558        }
5559    }
5560
5561    @Override
5562    public int checkUidSignatures(int uid1, int uid2) {
5563        final int callingUid = Binder.getCallingUid();
5564        final int callingUserId = UserHandle.getUserId(callingUid);
5565        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5566        // Map to base uids.
5567        uid1 = UserHandle.getAppId(uid1);
5568        uid2 = UserHandle.getAppId(uid2);
5569        // reader
5570        synchronized (mPackages) {
5571            Signature[] s1;
5572            Signature[] s2;
5573            Object obj = mSettings.getUserIdLPr(uid1);
5574            if (obj != null) {
5575                if (obj instanceof SharedUserSetting) {
5576                    if (isCallerInstantApp) {
5577                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5578                    }
5579                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5580                } else if (obj instanceof PackageSetting) {
5581                    final PackageSetting ps = (PackageSetting) obj;
5582                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5583                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5584                    }
5585                    s1 = ps.signatures.mSigningDetails.signatures;
5586                } else {
5587                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5588                }
5589            } else {
5590                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5591            }
5592            obj = mSettings.getUserIdLPr(uid2);
5593            if (obj != null) {
5594                if (obj instanceof SharedUserSetting) {
5595                    if (isCallerInstantApp) {
5596                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5597                    }
5598                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5599                } else if (obj instanceof PackageSetting) {
5600                    final PackageSetting ps = (PackageSetting) obj;
5601                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5602                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5603                    }
5604                    s2 = ps.signatures.mSigningDetails.signatures;
5605                } else {
5606                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5607                }
5608            } else {
5609                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5610            }
5611            return compareSignatures(s1, s2);
5612        }
5613    }
5614
5615    @Override
5616    public boolean hasSigningCertificate(
5617            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5618
5619        synchronized (mPackages) {
5620            final PackageParser.Package p = mPackages.get(packageName);
5621            if (p == null || p.mExtras == null) {
5622                return false;
5623            }
5624            final int callingUid = Binder.getCallingUid();
5625            final int callingUserId = UserHandle.getUserId(callingUid);
5626            final PackageSetting ps = (PackageSetting) p.mExtras;
5627            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5628                return false;
5629            }
5630            switch (type) {
5631                case CERT_INPUT_RAW_X509:
5632                    return p.mSigningDetails.hasCertificate(certificate);
5633                case CERT_INPUT_SHA256:
5634                    return p.mSigningDetails.hasSha256Certificate(certificate);
5635                default:
5636                    return false;
5637            }
5638        }
5639    }
5640
5641    @Override
5642    public boolean hasUidSigningCertificate(
5643            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5644        final int callingUid = Binder.getCallingUid();
5645        final int callingUserId = UserHandle.getUserId(callingUid);
5646        // Map to base uids.
5647        uid = UserHandle.getAppId(uid);
5648        // reader
5649        synchronized (mPackages) {
5650            final PackageParser.SigningDetails signingDetails;
5651            final Object obj = mSettings.getUserIdLPr(uid);
5652            if (obj != null) {
5653                if (obj instanceof SharedUserSetting) {
5654                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5655                    if (isCallerInstantApp) {
5656                        return false;
5657                    }
5658                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5659                } else if (obj instanceof PackageSetting) {
5660                    final PackageSetting ps = (PackageSetting) obj;
5661                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5662                        return false;
5663                    }
5664                    signingDetails = ps.signatures.mSigningDetails;
5665                } else {
5666                    return false;
5667                }
5668            } else {
5669                return false;
5670            }
5671            switch (type) {
5672                case CERT_INPUT_RAW_X509:
5673                    return signingDetails.hasCertificate(certificate);
5674                case CERT_INPUT_SHA256:
5675                    return signingDetails.hasSha256Certificate(certificate);
5676                default:
5677                    return false;
5678            }
5679        }
5680    }
5681
5682    /**
5683     * This method should typically only be used when granting or revoking
5684     * permissions, since the app may immediately restart after this call.
5685     * <p>
5686     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5687     * guard your work against the app being relaunched.
5688     */
5689    private void killUid(int appId, int userId, String reason) {
5690        final long identity = Binder.clearCallingIdentity();
5691        try {
5692            IActivityManager am = ActivityManager.getService();
5693            if (am != null) {
5694                try {
5695                    am.killUid(appId, userId, reason);
5696                } catch (RemoteException e) {
5697                    /* ignore - same process */
5698                }
5699            }
5700        } finally {
5701            Binder.restoreCallingIdentity(identity);
5702        }
5703    }
5704
5705    /**
5706     * If the database version for this type of package (internal storage or
5707     * external storage) is less than the version where package signatures
5708     * were updated, return true.
5709     */
5710    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5711        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5712        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5713    }
5714
5715    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5716        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5717        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5718    }
5719
5720    @Override
5721    public List<String> getAllPackages() {
5722        final int callingUid = Binder.getCallingUid();
5723        final int callingUserId = UserHandle.getUserId(callingUid);
5724        synchronized (mPackages) {
5725            if (canViewInstantApps(callingUid, callingUserId)) {
5726                return new ArrayList<String>(mPackages.keySet());
5727            }
5728            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5729            final List<String> result = new ArrayList<>();
5730            if (instantAppPkgName != null) {
5731                // caller is an instant application; filter unexposed applications
5732                for (PackageParser.Package pkg : mPackages.values()) {
5733                    if (!pkg.visibleToInstantApps) {
5734                        continue;
5735                    }
5736                    result.add(pkg.packageName);
5737                }
5738            } else {
5739                // caller is a normal application; filter instant applications
5740                for (PackageParser.Package pkg : mPackages.values()) {
5741                    final PackageSetting ps =
5742                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5743                    if (ps != null
5744                            && ps.getInstantApp(callingUserId)
5745                            && !mInstantAppRegistry.isInstantAccessGranted(
5746                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5747                        continue;
5748                    }
5749                    result.add(pkg.packageName);
5750                }
5751            }
5752            return result;
5753        }
5754    }
5755
5756    @Override
5757    public String[] getPackagesForUid(int uid) {
5758        final int callingUid = Binder.getCallingUid();
5759        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5760        final int userId = UserHandle.getUserId(uid);
5761        uid = UserHandle.getAppId(uid);
5762        // reader
5763        synchronized (mPackages) {
5764            Object obj = mSettings.getUserIdLPr(uid);
5765            if (obj instanceof SharedUserSetting) {
5766                if (isCallerInstantApp) {
5767                    return null;
5768                }
5769                final SharedUserSetting sus = (SharedUserSetting) obj;
5770                final int N = sus.packages.size();
5771                String[] res = new String[N];
5772                final Iterator<PackageSetting> it = sus.packages.iterator();
5773                int i = 0;
5774                while (it.hasNext()) {
5775                    PackageSetting ps = it.next();
5776                    if (ps.getInstalled(userId)) {
5777                        res[i++] = ps.name;
5778                    } else {
5779                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5780                    }
5781                }
5782                return res;
5783            } else if (obj instanceof PackageSetting) {
5784                final PackageSetting ps = (PackageSetting) obj;
5785                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5786                    return new String[]{ps.name};
5787                }
5788            }
5789        }
5790        return null;
5791    }
5792
5793    @Override
5794    public String getNameForUid(int uid) {
5795        final int callingUid = Binder.getCallingUid();
5796        if (getInstantAppPackageName(callingUid) != null) {
5797            return null;
5798        }
5799        synchronized (mPackages) {
5800            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5801            if (obj instanceof SharedUserSetting) {
5802                final SharedUserSetting sus = (SharedUserSetting) obj;
5803                return sus.name + ":" + sus.userId;
5804            } else if (obj instanceof PackageSetting) {
5805                final PackageSetting ps = (PackageSetting) obj;
5806                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5807                    return null;
5808                }
5809                return ps.name;
5810            }
5811            return null;
5812        }
5813    }
5814
5815    @Override
5816    public String[] getNamesForUids(int[] uids) {
5817        if (uids == null || uids.length == 0) {
5818            return null;
5819        }
5820        final int callingUid = Binder.getCallingUid();
5821        if (getInstantAppPackageName(callingUid) != null) {
5822            return null;
5823        }
5824        final String[] names = new String[uids.length];
5825        synchronized (mPackages) {
5826            for (int i = uids.length - 1; i >= 0; i--) {
5827                final int uid = uids[i];
5828                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5829                if (obj instanceof SharedUserSetting) {
5830                    final SharedUserSetting sus = (SharedUserSetting) obj;
5831                    names[i] = "shared:" + sus.name;
5832                } else if (obj instanceof PackageSetting) {
5833                    final PackageSetting ps = (PackageSetting) obj;
5834                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5835                        names[i] = null;
5836                    } else {
5837                        names[i] = ps.name;
5838                    }
5839                } else {
5840                    names[i] = null;
5841                }
5842            }
5843        }
5844        return names;
5845    }
5846
5847    @Override
5848    public int getUidForSharedUser(String sharedUserName) {
5849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5850            return -1;
5851        }
5852        if (sharedUserName == null) {
5853            return -1;
5854        }
5855        // reader
5856        synchronized (mPackages) {
5857            SharedUserSetting suid;
5858            try {
5859                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5860                if (suid != null) {
5861                    return suid.userId;
5862                }
5863            } catch (PackageManagerException ignore) {
5864                // can't happen, but, still need to catch it
5865            }
5866            return -1;
5867        }
5868    }
5869
5870    @Override
5871    public int getFlagsForUid(int uid) {
5872        final int callingUid = Binder.getCallingUid();
5873        if (getInstantAppPackageName(callingUid) != null) {
5874            return 0;
5875        }
5876        synchronized (mPackages) {
5877            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5878            if (obj instanceof SharedUserSetting) {
5879                final SharedUserSetting sus = (SharedUserSetting) obj;
5880                return sus.pkgFlags;
5881            } else if (obj instanceof PackageSetting) {
5882                final PackageSetting ps = (PackageSetting) obj;
5883                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5884                    return 0;
5885                }
5886                return ps.pkgFlags;
5887            }
5888        }
5889        return 0;
5890    }
5891
5892    @Override
5893    public int getPrivateFlagsForUid(int uid) {
5894        final int callingUid = Binder.getCallingUid();
5895        if (getInstantAppPackageName(callingUid) != null) {
5896            return 0;
5897        }
5898        synchronized (mPackages) {
5899            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5900            if (obj instanceof SharedUserSetting) {
5901                final SharedUserSetting sus = (SharedUserSetting) obj;
5902                return sus.pkgPrivateFlags;
5903            } else if (obj instanceof PackageSetting) {
5904                final PackageSetting ps = (PackageSetting) obj;
5905                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5906                    return 0;
5907                }
5908                return ps.pkgPrivateFlags;
5909            }
5910        }
5911        return 0;
5912    }
5913
5914    @Override
5915    public boolean isUidPrivileged(int uid) {
5916        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5917            return false;
5918        }
5919        uid = UserHandle.getAppId(uid);
5920        // reader
5921        synchronized (mPackages) {
5922            Object obj = mSettings.getUserIdLPr(uid);
5923            if (obj instanceof SharedUserSetting) {
5924                final SharedUserSetting sus = (SharedUserSetting) obj;
5925                final Iterator<PackageSetting> it = sus.packages.iterator();
5926                while (it.hasNext()) {
5927                    if (it.next().isPrivileged()) {
5928                        return true;
5929                    }
5930                }
5931            } else if (obj instanceof PackageSetting) {
5932                final PackageSetting ps = (PackageSetting) obj;
5933                return ps.isPrivileged();
5934            }
5935        }
5936        return false;
5937    }
5938
5939    @Override
5940    public String[] getAppOpPermissionPackages(String permName) {
5941        return mPermissionManager.getAppOpPermissionPackages(permName);
5942    }
5943
5944    @Override
5945    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5946            int flags, int userId) {
5947        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5948                Binder.getCallingUid());
5949    }
5950
5951    /**
5952     * Normally instant apps can only be resolved when they're visible to the caller.
5953     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5954     * since we need to allow the system to start any installed application.
5955     */
5956    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5957            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5958        try {
5959            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5960
5961            if (!sUserManager.exists(userId)) return null;
5962            final int callingUid = Binder.getCallingUid();
5963            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5964            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5965                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5966
5967            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5968            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5969                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5970            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5971
5972            final ResolveInfo bestChoice =
5973                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5974            return bestChoice;
5975        } finally {
5976            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5977        }
5978    }
5979
5980    @Override
5981    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5982        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5983            throw new SecurityException(
5984                    "findPersistentPreferredActivity can only be run by the system");
5985        }
5986        if (!sUserManager.exists(userId)) {
5987            return null;
5988        }
5989        final int callingUid = Binder.getCallingUid();
5990        intent = updateIntentForResolve(intent);
5991        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5992        final int flags = updateFlagsForResolve(
5993                0, userId, intent, callingUid, false /*includeInstantApps*/);
5994        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5995                userId);
5996        synchronized (mPackages) {
5997            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5998                    userId);
5999        }
6000    }
6001
6002    @Override
6003    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6004            IntentFilter filter, int match, ComponentName activity) {
6005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6006            return;
6007        }
6008        final int userId = UserHandle.getCallingUserId();
6009        if (DEBUG_PREFERRED) {
6010            Log.v(TAG, "setLastChosenActivity intent=" + intent
6011                + " resolvedType=" + resolvedType
6012                + " flags=" + flags
6013                + " filter=" + filter
6014                + " match=" + match
6015                + " activity=" + activity);
6016            filter.dump(new PrintStreamPrinter(System.out), "    ");
6017        }
6018        intent.setComponent(null);
6019        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6020                userId);
6021        // Find any earlier preferred or last chosen entries and nuke them
6022        findPreferredActivity(intent, resolvedType,
6023                flags, query, 0, false, true, false, userId);
6024        // Add the new activity as the last chosen for this filter
6025        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6026                "Setting last chosen");
6027    }
6028
6029    @Override
6030    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6032            return null;
6033        }
6034        final int userId = UserHandle.getCallingUserId();
6035        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6036        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6037                userId);
6038        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6039                false, false, false, userId);
6040    }
6041
6042    /**
6043     * Returns whether or not instant apps have been disabled remotely.
6044     */
6045    private boolean areWebInstantAppsDisabled() {
6046        return mWebInstantAppsDisabled;
6047    }
6048
6049    private boolean isInstantAppResolutionAllowed(
6050            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6051            boolean skipPackageCheck) {
6052        if (mInstantAppResolverConnection == null) {
6053            return false;
6054        }
6055        if (mInstantAppInstallerActivity == null) {
6056            return false;
6057        }
6058        if (intent.getComponent() != null) {
6059            return false;
6060        }
6061        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6062            return false;
6063        }
6064        if (!skipPackageCheck && intent.getPackage() != null) {
6065            return false;
6066        }
6067        if (!intent.isWebIntent()) {
6068            // for non web intents, we should not resolve externally if an app already exists to
6069            // handle it or if the caller didn't explicitly request it.
6070            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6071                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6072                return false;
6073            }
6074        } else {
6075            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6076                return false;
6077            } else if (areWebInstantAppsDisabled()) {
6078                return false;
6079            }
6080        }
6081        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6082        // Or if there's already an ephemeral app installed that handles the action
6083        synchronized (mPackages) {
6084            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6085            for (int n = 0; n < count; n++) {
6086                final ResolveInfo info = resolvedActivities.get(n);
6087                final String packageName = info.activityInfo.packageName;
6088                final PackageSetting ps = mSettings.mPackages.get(packageName);
6089                if (ps != null) {
6090                    // only check domain verification status if the app is not a browser
6091                    if (!info.handleAllWebDataURI) {
6092                        // Try to get the status from User settings first
6093                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6094                        final int status = (int) (packedStatus >> 32);
6095                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6096                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6097                            if (DEBUG_INSTANT) {
6098                                Slog.v(TAG, "DENY instant app;"
6099                                    + " pkg: " + packageName + ", status: " + status);
6100                            }
6101                            return false;
6102                        }
6103                    }
6104                    if (ps.getInstantApp(userId)) {
6105                        if (DEBUG_INSTANT) {
6106                            Slog.v(TAG, "DENY instant app installed;"
6107                                    + " pkg: " + packageName);
6108                        }
6109                        return false;
6110                    }
6111                }
6112            }
6113        }
6114        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6115        return true;
6116    }
6117
6118    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6119            Intent origIntent, String resolvedType, String callingPackage,
6120            Bundle verificationBundle, int userId) {
6121        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6122                new InstantAppRequest(responseObj, origIntent, resolvedType,
6123                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6124        mHandler.sendMessage(msg);
6125    }
6126
6127    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6128            int flags, List<ResolveInfo> query, int userId) {
6129        if (query != null) {
6130            final int N = query.size();
6131            if (N == 1) {
6132                return query.get(0);
6133            } else if (N > 1) {
6134                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6135                // If there is more than one activity with the same priority,
6136                // then let the user decide between them.
6137                ResolveInfo r0 = query.get(0);
6138                ResolveInfo r1 = query.get(1);
6139                if (DEBUG_INTENT_MATCHING || debug) {
6140                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6141                            + r1.activityInfo.name + "=" + r1.priority);
6142                }
6143                // If the first activity has a higher priority, or a different
6144                // default, then it is always desirable to pick it.
6145                if (r0.priority != r1.priority
6146                        || r0.preferredOrder != r1.preferredOrder
6147                        || r0.isDefault != r1.isDefault) {
6148                    return query.get(0);
6149                }
6150                // If we have saved a preference for a preferred activity for
6151                // this Intent, use that.
6152                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6153                        flags, query, r0.priority, true, false, debug, userId);
6154                if (ri != null) {
6155                    return ri;
6156                }
6157                // If we have an ephemeral app, use it
6158                for (int i = 0; i < N; i++) {
6159                    ri = query.get(i);
6160                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6161                        final String packageName = ri.activityInfo.packageName;
6162                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6163                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6164                        final int status = (int)(packedStatus >> 32);
6165                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6166                            return ri;
6167                        }
6168                    }
6169                }
6170                ri = new ResolveInfo(mResolveInfo);
6171                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6172                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6173                // If all of the options come from the same package, show the application's
6174                // label and icon instead of the generic resolver's.
6175                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6176                // and then throw away the ResolveInfo itself, meaning that the caller loses
6177                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6178                // a fallback for this case; we only set the target package's resources on
6179                // the ResolveInfo, not the ActivityInfo.
6180                final String intentPackage = intent.getPackage();
6181                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6182                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6183                    ri.resolvePackageName = intentPackage;
6184                    if (userNeedsBadging(userId)) {
6185                        ri.noResourceId = true;
6186                    } else {
6187                        ri.icon = appi.icon;
6188                    }
6189                    ri.iconResourceId = appi.icon;
6190                    ri.labelRes = appi.labelRes;
6191                }
6192                ri.activityInfo.applicationInfo = new ApplicationInfo(
6193                        ri.activityInfo.applicationInfo);
6194                if (userId != 0) {
6195                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6196                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6197                }
6198                // Make sure that the resolver is displayable in car mode
6199                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6200                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6201                return ri;
6202            }
6203        }
6204        return null;
6205    }
6206
6207    /**
6208     * Return true if the given list is not empty and all of its contents have
6209     * an activityInfo with the given package name.
6210     */
6211    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6212        if (ArrayUtils.isEmpty(list)) {
6213            return false;
6214        }
6215        for (int i = 0, N = list.size(); i < N; i++) {
6216            final ResolveInfo ri = list.get(i);
6217            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6218            if (ai == null || !packageName.equals(ai.packageName)) {
6219                return false;
6220            }
6221        }
6222        return true;
6223    }
6224
6225    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6226            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6227        final int N = query.size();
6228        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6229                .get(userId);
6230        // Get the list of persistent preferred activities that handle the intent
6231        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6232        List<PersistentPreferredActivity> pprefs = ppir != null
6233                ? ppir.queryIntent(intent, resolvedType,
6234                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6235                        userId)
6236                : null;
6237        if (pprefs != null && pprefs.size() > 0) {
6238            final int M = pprefs.size();
6239            for (int i=0; i<M; i++) {
6240                final PersistentPreferredActivity ppa = pprefs.get(i);
6241                if (DEBUG_PREFERRED || debug) {
6242                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6243                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6244                            + "\n  component=" + ppa.mComponent);
6245                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6246                }
6247                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6248                        flags | MATCH_DISABLED_COMPONENTS, userId);
6249                if (DEBUG_PREFERRED || debug) {
6250                    Slog.v(TAG, "Found persistent preferred activity:");
6251                    if (ai != null) {
6252                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6253                    } else {
6254                        Slog.v(TAG, "  null");
6255                    }
6256                }
6257                if (ai == null) {
6258                    // This previously registered persistent preferred activity
6259                    // component is no longer known. Ignore it and do NOT remove it.
6260                    continue;
6261                }
6262                for (int j=0; j<N; j++) {
6263                    final ResolveInfo ri = query.get(j);
6264                    if (!ri.activityInfo.applicationInfo.packageName
6265                            .equals(ai.applicationInfo.packageName)) {
6266                        continue;
6267                    }
6268                    if (!ri.activityInfo.name.equals(ai.name)) {
6269                        continue;
6270                    }
6271                    //  Found a persistent preference that can handle the intent.
6272                    if (DEBUG_PREFERRED || debug) {
6273                        Slog.v(TAG, "Returning persistent preferred activity: " +
6274                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6275                    }
6276                    return ri;
6277                }
6278            }
6279        }
6280        return null;
6281    }
6282
6283    // TODO: handle preferred activities missing while user has amnesia
6284    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6285            List<ResolveInfo> query, int priority, boolean always,
6286            boolean removeMatches, boolean debug, int userId) {
6287        if (!sUserManager.exists(userId)) return null;
6288        final int callingUid = Binder.getCallingUid();
6289        flags = updateFlagsForResolve(
6290                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6291        intent = updateIntentForResolve(intent);
6292        // writer
6293        synchronized (mPackages) {
6294            // Try to find a matching persistent preferred activity.
6295            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6296                    debug, userId);
6297
6298            // If a persistent preferred activity matched, use it.
6299            if (pri != null) {
6300                return pri;
6301            }
6302
6303            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6304            // Get the list of preferred activities that handle the intent
6305            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6306            List<PreferredActivity> prefs = pir != null
6307                    ? pir.queryIntent(intent, resolvedType,
6308                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6309                            userId)
6310                    : null;
6311            if (prefs != null && prefs.size() > 0) {
6312                boolean changed = false;
6313                try {
6314                    // First figure out how good the original match set is.
6315                    // We will only allow preferred activities that came
6316                    // from the same match quality.
6317                    int match = 0;
6318
6319                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6320
6321                    final int N = query.size();
6322                    for (int j=0; j<N; j++) {
6323                        final ResolveInfo ri = query.get(j);
6324                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6325                                + ": 0x" + Integer.toHexString(match));
6326                        if (ri.match > match) {
6327                            match = ri.match;
6328                        }
6329                    }
6330
6331                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6332                            + Integer.toHexString(match));
6333
6334                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6335                    final int M = prefs.size();
6336                    for (int i=0; i<M; i++) {
6337                        final PreferredActivity pa = prefs.get(i);
6338                        if (DEBUG_PREFERRED || debug) {
6339                            Slog.v(TAG, "Checking PreferredActivity ds="
6340                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6341                                    + "\n  component=" + pa.mPref.mComponent);
6342                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6343                        }
6344                        if (pa.mPref.mMatch != match) {
6345                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6346                                    + Integer.toHexString(pa.mPref.mMatch));
6347                            continue;
6348                        }
6349                        // If it's not an "always" type preferred activity and that's what we're
6350                        // looking for, skip it.
6351                        if (always && !pa.mPref.mAlways) {
6352                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6353                            continue;
6354                        }
6355                        final ActivityInfo ai = getActivityInfo(
6356                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6357                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6358                                userId);
6359                        if (DEBUG_PREFERRED || debug) {
6360                            Slog.v(TAG, "Found preferred activity:");
6361                            if (ai != null) {
6362                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6363                            } else {
6364                                Slog.v(TAG, "  null");
6365                            }
6366                        }
6367                        if (ai == null) {
6368                            // This previously registered preferred activity
6369                            // component is no longer known.  Most likely an update
6370                            // to the app was installed and in the new version this
6371                            // component no longer exists.  Clean it up by removing
6372                            // it from the preferred activities list, and skip it.
6373                            Slog.w(TAG, "Removing dangling preferred activity: "
6374                                    + pa.mPref.mComponent);
6375                            pir.removeFilter(pa);
6376                            changed = true;
6377                            continue;
6378                        }
6379                        for (int j=0; j<N; j++) {
6380                            final ResolveInfo ri = query.get(j);
6381                            if (!ri.activityInfo.applicationInfo.packageName
6382                                    .equals(ai.applicationInfo.packageName)) {
6383                                continue;
6384                            }
6385                            if (!ri.activityInfo.name.equals(ai.name)) {
6386                                continue;
6387                            }
6388
6389                            if (removeMatches) {
6390                                pir.removeFilter(pa);
6391                                changed = true;
6392                                if (DEBUG_PREFERRED) {
6393                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6394                                }
6395                                break;
6396                            }
6397
6398                            // Okay we found a previously set preferred or last chosen app.
6399                            // If the result set is different from when this
6400                            // was created, and is not a subset of the preferred set, we need to
6401                            // clear it and re-ask the user their preference, if we're looking for
6402                            // an "always" type entry.
6403                            if (always && !pa.mPref.sameSet(query)) {
6404                                if (pa.mPref.isSuperset(query)) {
6405                                    // some components of the set are no longer present in
6406                                    // the query, but the preferred activity can still be reused
6407                                    if (DEBUG_PREFERRED) {
6408                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6409                                                + " still valid as only non-preferred components"
6410                                                + " were removed for " + intent + " type "
6411                                                + resolvedType);
6412                                    }
6413                                    // remove obsolete components and re-add the up-to-date filter
6414                                    PreferredActivity freshPa = new PreferredActivity(pa,
6415                                            pa.mPref.mMatch,
6416                                            pa.mPref.discardObsoleteComponents(query),
6417                                            pa.mPref.mComponent,
6418                                            pa.mPref.mAlways);
6419                                    pir.removeFilter(pa);
6420                                    pir.addFilter(freshPa);
6421                                    changed = true;
6422                                } else {
6423                                    Slog.i(TAG,
6424                                            "Result set changed, dropping preferred activity for "
6425                                                    + intent + " type " + resolvedType);
6426                                    if (DEBUG_PREFERRED) {
6427                                        Slog.v(TAG, "Removing preferred activity since set changed "
6428                                                + pa.mPref.mComponent);
6429                                    }
6430                                    pir.removeFilter(pa);
6431                                    // Re-add the filter as a "last chosen" entry (!always)
6432                                    PreferredActivity lastChosen = new PreferredActivity(
6433                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6434                                    pir.addFilter(lastChosen);
6435                                    changed = true;
6436                                    return null;
6437                                }
6438                            }
6439
6440                            // Yay! Either the set matched or we're looking for the last chosen
6441                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6442                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6443                            return ri;
6444                        }
6445                    }
6446                } finally {
6447                    if (changed) {
6448                        if (DEBUG_PREFERRED) {
6449                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6450                        }
6451                        scheduleWritePackageRestrictionsLocked(userId);
6452                    }
6453                }
6454            }
6455        }
6456        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6457        return null;
6458    }
6459
6460    /*
6461     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6462     */
6463    @Override
6464    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6465            int targetUserId) {
6466        mContext.enforceCallingOrSelfPermission(
6467                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6468        List<CrossProfileIntentFilter> matches =
6469                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6470        if (matches != null) {
6471            int size = matches.size();
6472            for (int i = 0; i < size; i++) {
6473                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6474            }
6475        }
6476        if (intent.hasWebURI()) {
6477            // cross-profile app linking works only towards the parent.
6478            final int callingUid = Binder.getCallingUid();
6479            final UserInfo parent = getProfileParent(sourceUserId);
6480            synchronized(mPackages) {
6481                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6482                        false /*includeInstantApps*/);
6483                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6484                        intent, resolvedType, flags, sourceUserId, parent.id);
6485                return xpDomainInfo != null;
6486            }
6487        }
6488        return false;
6489    }
6490
6491    private UserInfo getProfileParent(int userId) {
6492        final long identity = Binder.clearCallingIdentity();
6493        try {
6494            return sUserManager.getProfileParent(userId);
6495        } finally {
6496            Binder.restoreCallingIdentity(identity);
6497        }
6498    }
6499
6500    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6501            String resolvedType, int userId) {
6502        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6503        if (resolver != null) {
6504            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6505        }
6506        return null;
6507    }
6508
6509    @Override
6510    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6511            String resolvedType, int flags, int userId) {
6512        try {
6513            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6514
6515            return new ParceledListSlice<>(
6516                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6517        } finally {
6518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6519        }
6520    }
6521
6522    /**
6523     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6524     * instant, returns {@code null}.
6525     */
6526    private String getInstantAppPackageName(int callingUid) {
6527        synchronized (mPackages) {
6528            // If the caller is an isolated app use the owner's uid for the lookup.
6529            if (Process.isIsolated(callingUid)) {
6530                callingUid = mIsolatedOwners.get(callingUid);
6531            }
6532            final int appId = UserHandle.getAppId(callingUid);
6533            final Object obj = mSettings.getUserIdLPr(appId);
6534            if (obj instanceof PackageSetting) {
6535                final PackageSetting ps = (PackageSetting) obj;
6536                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6537                return isInstantApp ? ps.pkg.packageName : null;
6538            }
6539        }
6540        return null;
6541    }
6542
6543    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6544            String resolvedType, int flags, int userId) {
6545        return queryIntentActivitiesInternal(
6546                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6547                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6548    }
6549
6550    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6551            String resolvedType, int flags, int filterCallingUid, int userId,
6552            boolean resolveForStart, boolean allowDynamicSplits) {
6553        if (!sUserManager.exists(userId)) return Collections.emptyList();
6554        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6555        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6556                false /* requireFullPermission */, false /* checkShell */,
6557                "query intent activities");
6558        final String pkgName = intent.getPackage();
6559        ComponentName comp = intent.getComponent();
6560        if (comp == null) {
6561            if (intent.getSelector() != null) {
6562                intent = intent.getSelector();
6563                comp = intent.getComponent();
6564            }
6565        }
6566
6567        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6568                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6569        if (comp != null) {
6570            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6571            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6572            if (ai != null) {
6573                // When specifying an explicit component, we prevent the activity from being
6574                // used when either 1) the calling package is normal and the activity is within
6575                // an ephemeral application or 2) the calling package is ephemeral and the
6576                // activity is not visible to ephemeral applications.
6577                final boolean matchInstantApp =
6578                        (flags & PackageManager.MATCH_INSTANT) != 0;
6579                final boolean matchVisibleToInstantAppOnly =
6580                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6581                final boolean matchExplicitlyVisibleOnly =
6582                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6583                final boolean isCallerInstantApp =
6584                        instantAppPkgName != null;
6585                final boolean isTargetSameInstantApp =
6586                        comp.getPackageName().equals(instantAppPkgName);
6587                final boolean isTargetInstantApp =
6588                        (ai.applicationInfo.privateFlags
6589                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6590                final boolean isTargetVisibleToInstantApp =
6591                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6592                final boolean isTargetExplicitlyVisibleToInstantApp =
6593                        isTargetVisibleToInstantApp
6594                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6595                final boolean isTargetHiddenFromInstantApp =
6596                        !isTargetVisibleToInstantApp
6597                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6598                final boolean blockResolution =
6599                        !isTargetSameInstantApp
6600                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6601                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6602                                        && isTargetHiddenFromInstantApp));
6603                if (!blockResolution) {
6604                    final ResolveInfo ri = new ResolveInfo();
6605                    ri.activityInfo = ai;
6606                    list.add(ri);
6607                }
6608            }
6609            return applyPostResolutionFilter(
6610                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6611        }
6612
6613        // reader
6614        boolean sortResult = false;
6615        boolean addInstant = false;
6616        List<ResolveInfo> result;
6617        synchronized (mPackages) {
6618            if (pkgName == null) {
6619                List<CrossProfileIntentFilter> matchingFilters =
6620                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6621                // Check for results that need to skip the current profile.
6622                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6623                        resolvedType, flags, userId);
6624                if (xpResolveInfo != null) {
6625                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6626                    xpResult.add(xpResolveInfo);
6627                    return applyPostResolutionFilter(
6628                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6629                            allowDynamicSplits, filterCallingUid, userId, intent);
6630                }
6631
6632                // Check for results in the current profile.
6633                result = filterIfNotSystemUser(mActivities.queryIntent(
6634                        intent, resolvedType, flags, userId), userId);
6635                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6636                        false /*skipPackageCheck*/);
6637                // Check for cross profile results.
6638                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6639                xpResolveInfo = queryCrossProfileIntents(
6640                        matchingFilters, intent, resolvedType, flags, userId,
6641                        hasNonNegativePriorityResult);
6642                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6643                    boolean isVisibleToUser = filterIfNotSystemUser(
6644                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6645                    if (isVisibleToUser) {
6646                        result.add(xpResolveInfo);
6647                        sortResult = true;
6648                    }
6649                }
6650                if (intent.hasWebURI()) {
6651                    CrossProfileDomainInfo xpDomainInfo = null;
6652                    final UserInfo parent = getProfileParent(userId);
6653                    if (parent != null) {
6654                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6655                                flags, userId, parent.id);
6656                    }
6657                    if (xpDomainInfo != null) {
6658                        if (xpResolveInfo != null) {
6659                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6660                            // in the result.
6661                            result.remove(xpResolveInfo);
6662                        }
6663                        if (result.size() == 0 && !addInstant) {
6664                            // No result in current profile, but found candidate in parent user.
6665                            // And we are not going to add emphemeral app, so we can return the
6666                            // result straight away.
6667                            result.add(xpDomainInfo.resolveInfo);
6668                            return applyPostResolutionFilter(result, instantAppPkgName,
6669                                    allowDynamicSplits, filterCallingUid, userId, intent);
6670                        }
6671                    } else if (result.size() <= 1 && !addInstant) {
6672                        // No result in parent user and <= 1 result in current profile, and we
6673                        // are not going to add emphemeral app, so we can return the result without
6674                        // further processing.
6675                        return applyPostResolutionFilter(result, instantAppPkgName,
6676                                allowDynamicSplits, filterCallingUid, userId, intent);
6677                    }
6678                    // We have more than one candidate (combining results from current and parent
6679                    // profile), so we need filtering and sorting.
6680                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6681                            intent, flags, result, xpDomainInfo, userId);
6682                    sortResult = true;
6683                }
6684            } else {
6685                final PackageParser.Package pkg = mPackages.get(pkgName);
6686                result = null;
6687                if (pkg != null) {
6688                    result = filterIfNotSystemUser(
6689                            mActivities.queryIntentForPackage(
6690                                    intent, resolvedType, flags, pkg.activities, userId),
6691                            userId);
6692                }
6693                if (result == null || result.size() == 0) {
6694                    // the caller wants to resolve for a particular package; however, there
6695                    // were no installed results, so, try to find an ephemeral result
6696                    addInstant = isInstantAppResolutionAllowed(
6697                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6698                    if (result == null) {
6699                        result = new ArrayList<>();
6700                    }
6701                }
6702            }
6703        }
6704        if (addInstant) {
6705            result = maybeAddInstantAppInstaller(
6706                    result, intent, resolvedType, flags, userId, resolveForStart);
6707        }
6708        if (sortResult) {
6709            Collections.sort(result, mResolvePrioritySorter);
6710        }
6711        return applyPostResolutionFilter(
6712                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6713    }
6714
6715    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6716            String resolvedType, int flags, int userId, boolean resolveForStart) {
6717        // first, check to see if we've got an instant app already installed
6718        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6719        ResolveInfo localInstantApp = null;
6720        boolean blockResolution = false;
6721        if (!alreadyResolvedLocally) {
6722            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6723                    flags
6724                        | PackageManager.GET_RESOLVED_FILTER
6725                        | PackageManager.MATCH_INSTANT
6726                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6727                    userId);
6728            for (int i = instantApps.size() - 1; i >= 0; --i) {
6729                final ResolveInfo info = instantApps.get(i);
6730                final String packageName = info.activityInfo.packageName;
6731                final PackageSetting ps = mSettings.mPackages.get(packageName);
6732                if (ps.getInstantApp(userId)) {
6733                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6734                    final int status = (int)(packedStatus >> 32);
6735                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6736                        // there's a local instant application installed, but, the user has
6737                        // chosen to never use it; skip resolution and don't acknowledge
6738                        // an instant application is even available
6739                        if (DEBUG_INSTANT) {
6740                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6741                        }
6742                        blockResolution = true;
6743                        break;
6744                    } else {
6745                        // we have a locally installed instant application; skip resolution
6746                        // but acknowledge there's an instant application available
6747                        if (DEBUG_INSTANT) {
6748                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6749                        }
6750                        localInstantApp = info;
6751                        break;
6752                    }
6753                }
6754            }
6755        }
6756        // no app installed, let's see if one's available
6757        AuxiliaryResolveInfo auxiliaryResponse = null;
6758        if (!blockResolution) {
6759            if (localInstantApp == null) {
6760                // we don't have an instant app locally, resolve externally
6761                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6762                final InstantAppRequest requestObject = new InstantAppRequest(
6763                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6764                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6765                        resolveForStart);
6766                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6767                        mInstantAppResolverConnection, requestObject);
6768                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6769            } else {
6770                // we have an instant application locally, but, we can't admit that since
6771                // callers shouldn't be able to determine prior browsing. create a dummy
6772                // auxiliary response so the downstream code behaves as if there's an
6773                // instant application available externally. when it comes time to start
6774                // the instant application, we'll do the right thing.
6775                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6776                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6777                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6778            }
6779        }
6780        if (intent.isWebIntent() && auxiliaryResponse == null) {
6781            return result;
6782        }
6783        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6784        if (ps == null
6785                || ps.getUserState().get(userId) == null
6786                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6787            return result;
6788        }
6789        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6790        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6791                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6792        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6793                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6794        // add a non-generic filter
6795        ephemeralInstaller.filter = new IntentFilter();
6796        if (intent.getAction() != null) {
6797            ephemeralInstaller.filter.addAction(intent.getAction());
6798        }
6799        if (intent.getData() != null && intent.getData().getPath() != null) {
6800            ephemeralInstaller.filter.addDataPath(
6801                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6802        }
6803        ephemeralInstaller.isInstantAppAvailable = true;
6804        // make sure this resolver is the default
6805        ephemeralInstaller.isDefault = true;
6806        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6807        if (DEBUG_INSTANT) {
6808            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6809        }
6810
6811        result.add(ephemeralInstaller);
6812        return result;
6813    }
6814
6815    private static class CrossProfileDomainInfo {
6816        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6817        ResolveInfo resolveInfo;
6818        /* Best domain verification status of the activities found in the other profile */
6819        int bestDomainVerificationStatus;
6820    }
6821
6822    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6823            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6824        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6825                sourceUserId)) {
6826            return null;
6827        }
6828        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6829                resolvedType, flags, parentUserId);
6830
6831        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6832            return null;
6833        }
6834        CrossProfileDomainInfo result = null;
6835        int size = resultTargetUser.size();
6836        for (int i = 0; i < size; i++) {
6837            ResolveInfo riTargetUser = resultTargetUser.get(i);
6838            // Intent filter verification is only for filters that specify a host. So don't return
6839            // those that handle all web uris.
6840            if (riTargetUser.handleAllWebDataURI) {
6841                continue;
6842            }
6843            String packageName = riTargetUser.activityInfo.packageName;
6844            PackageSetting ps = mSettings.mPackages.get(packageName);
6845            if (ps == null) {
6846                continue;
6847            }
6848            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6849            int status = (int)(verificationState >> 32);
6850            if (result == null) {
6851                result = new CrossProfileDomainInfo();
6852                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6853                        sourceUserId, parentUserId);
6854                result.bestDomainVerificationStatus = status;
6855            } else {
6856                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6857                        result.bestDomainVerificationStatus);
6858            }
6859        }
6860        // Don't consider matches with status NEVER across profiles.
6861        if (result != null && result.bestDomainVerificationStatus
6862                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6863            return null;
6864        }
6865        return result;
6866    }
6867
6868    /**
6869     * Verification statuses are ordered from the worse to the best, except for
6870     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6871     */
6872    private int bestDomainVerificationStatus(int status1, int status2) {
6873        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6874            return status2;
6875        }
6876        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6877            return status1;
6878        }
6879        return (int) MathUtils.max(status1, status2);
6880    }
6881
6882    private boolean isUserEnabled(int userId) {
6883        long callingId = Binder.clearCallingIdentity();
6884        try {
6885            UserInfo userInfo = sUserManager.getUserInfo(userId);
6886            return userInfo != null && userInfo.isEnabled();
6887        } finally {
6888            Binder.restoreCallingIdentity(callingId);
6889        }
6890    }
6891
6892    /**
6893     * Filter out activities with systemUserOnly flag set, when current user is not System.
6894     *
6895     * @return filtered list
6896     */
6897    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6898        if (userId == UserHandle.USER_SYSTEM) {
6899            return resolveInfos;
6900        }
6901        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6902            ResolveInfo info = resolveInfos.get(i);
6903            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6904                resolveInfos.remove(i);
6905            }
6906        }
6907        return resolveInfos;
6908    }
6909
6910    /**
6911     * Filters out ephemeral activities.
6912     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6913     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6914     *
6915     * @param resolveInfos The pre-filtered list of resolved activities
6916     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6917     *          is performed.
6918     * @param intent
6919     * @return A filtered list of resolved activities.
6920     */
6921    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6922            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6923            Intent intent) {
6924        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6925        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6926            final ResolveInfo info = resolveInfos.get(i);
6927            // remove locally resolved instant app web results when disabled
6928            if (info.isInstantAppAvailable && blockInstant) {
6929                resolveInfos.remove(i);
6930                continue;
6931            }
6932            // allow activities that are defined in the provided package
6933            if (allowDynamicSplits
6934                    && info.activityInfo != null
6935                    && info.activityInfo.splitName != null
6936                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6937                            info.activityInfo.splitName)) {
6938                if (mInstantAppInstallerActivity == null) {
6939                    if (DEBUG_INSTALL) {
6940                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6941                    }
6942                    resolveInfos.remove(i);
6943                    continue;
6944                }
6945                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6946                    resolveInfos.remove(i);
6947                    continue;
6948                }
6949                // requested activity is defined in a split that hasn't been installed yet.
6950                // add the installer to the resolve list
6951                if (DEBUG_INSTALL) {
6952                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6953                }
6954                final ResolveInfo installerInfo = new ResolveInfo(
6955                        mInstantAppInstallerInfo);
6956                final ComponentName installFailureActivity = findInstallFailureActivity(
6957                        info.activityInfo.packageName,  filterCallingUid, userId);
6958                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6959                        installFailureActivity,
6960                        info.activityInfo.packageName,
6961                        info.activityInfo.applicationInfo.longVersionCode,
6962                        info.activityInfo.splitName);
6963                // add a non-generic filter
6964                installerInfo.filter = new IntentFilter();
6965
6966                // This resolve info may appear in the chooser UI, so let us make it
6967                // look as the one it replaces as far as the user is concerned which
6968                // requires loading the correct label and icon for the resolve info.
6969                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6970                installerInfo.labelRes = info.resolveLabelResId();
6971                installerInfo.icon = info.resolveIconResId();
6972                installerInfo.isInstantAppAvailable = true;
6973                resolveInfos.set(i, installerInfo);
6974                continue;
6975            }
6976            // caller is a full app, don't need to apply any other filtering
6977            if (ephemeralPkgName == null) {
6978                continue;
6979            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6980                // caller is same app; don't need to apply any other filtering
6981                continue;
6982            }
6983            // allow activities that have been explicitly exposed to ephemeral apps
6984            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6985            if (!isEphemeralApp
6986                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6987                continue;
6988            }
6989            resolveInfos.remove(i);
6990        }
6991        return resolveInfos;
6992    }
6993
6994    /**
6995     * Returns the activity component that can handle install failures.
6996     * <p>By default, the instant application installer handles failures. However, an
6997     * application may want to handle failures on its own. Applications do this by
6998     * creating an activity with an intent filter that handles the action
6999     * {@link Intent#ACTION_INSTALL_FAILURE}.
7000     */
7001    private @Nullable ComponentName findInstallFailureActivity(
7002            String packageName, int filterCallingUid, int userId) {
7003        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7004        failureActivityIntent.setPackage(packageName);
7005        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7006        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7007                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7008                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7009        final int NR = result.size();
7010        if (NR > 0) {
7011            for (int i = 0; i < NR; i++) {
7012                final ResolveInfo info = result.get(i);
7013                if (info.activityInfo.splitName != null) {
7014                    continue;
7015                }
7016                return new ComponentName(packageName, info.activityInfo.name);
7017            }
7018        }
7019        return null;
7020    }
7021
7022    /**
7023     * @param resolveInfos list of resolve infos in descending priority order
7024     * @return if the list contains a resolve info with non-negative priority
7025     */
7026    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7027        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7028    }
7029
7030    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7031            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7032            int userId) {
7033        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7034
7035        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7036            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7037                    candidates.size());
7038        }
7039
7040        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7041        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7042        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7043        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7044        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7045        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7046
7047        synchronized (mPackages) {
7048            final int count = candidates.size();
7049            // First, try to use linked apps. Partition the candidates into four lists:
7050            // one for the final results, one for the "do not use ever", one for "undefined status"
7051            // and finally one for "browser app type".
7052            for (int n=0; n<count; n++) {
7053                ResolveInfo info = candidates.get(n);
7054                String packageName = info.activityInfo.packageName;
7055                PackageSetting ps = mSettings.mPackages.get(packageName);
7056                if (ps != null) {
7057                    // Add to the special match all list (Browser use case)
7058                    if (info.handleAllWebDataURI) {
7059                        matchAllList.add(info);
7060                        continue;
7061                    }
7062                    // Try to get the status from User settings first
7063                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7064                    int status = (int)(packedStatus >> 32);
7065                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7066                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7067                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7068                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7069                                    + " : linkgen=" + linkGeneration);
7070                        }
7071                        // Use link-enabled generation as preferredOrder, i.e.
7072                        // prefer newly-enabled over earlier-enabled.
7073                        info.preferredOrder = linkGeneration;
7074                        alwaysList.add(info);
7075                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7076                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7077                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7078                        }
7079                        neverList.add(info);
7080                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7081                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7082                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7083                        }
7084                        alwaysAskList.add(info);
7085                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7086                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7087                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7088                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7089                        }
7090                        undefinedList.add(info);
7091                    }
7092                }
7093            }
7094
7095            // We'll want to include browser possibilities in a few cases
7096            boolean includeBrowser = false;
7097
7098            // First try to add the "always" resolution(s) for the current user, if any
7099            if (alwaysList.size() > 0) {
7100                result.addAll(alwaysList);
7101            } else {
7102                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7103                result.addAll(undefinedList);
7104                // Maybe add one for the other profile.
7105                if (xpDomainInfo != null && (
7106                        xpDomainInfo.bestDomainVerificationStatus
7107                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7108                    result.add(xpDomainInfo.resolveInfo);
7109                }
7110                includeBrowser = true;
7111            }
7112
7113            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7114            // If there were 'always' entries their preferred order has been set, so we also
7115            // back that off to make the alternatives equivalent
7116            if (alwaysAskList.size() > 0) {
7117                for (ResolveInfo i : result) {
7118                    i.preferredOrder = 0;
7119                }
7120                result.addAll(alwaysAskList);
7121                includeBrowser = true;
7122            }
7123
7124            if (includeBrowser) {
7125                // Also add browsers (all of them or only the default one)
7126                if (DEBUG_DOMAIN_VERIFICATION) {
7127                    Slog.v(TAG, "   ...including browsers in candidate set");
7128                }
7129                if ((matchFlags & MATCH_ALL) != 0) {
7130                    result.addAll(matchAllList);
7131                } else {
7132                    // Browser/generic handling case.  If there's a default browser, go straight
7133                    // to that (but only if there is no other higher-priority match).
7134                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7135                    int maxMatchPrio = 0;
7136                    ResolveInfo defaultBrowserMatch = null;
7137                    final int numCandidates = matchAllList.size();
7138                    for (int n = 0; n < numCandidates; n++) {
7139                        ResolveInfo info = matchAllList.get(n);
7140                        // track the highest overall match priority...
7141                        if (info.priority > maxMatchPrio) {
7142                            maxMatchPrio = info.priority;
7143                        }
7144                        // ...and the highest-priority default browser match
7145                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7146                            if (defaultBrowserMatch == null
7147                                    || (defaultBrowserMatch.priority < info.priority)) {
7148                                if (debug) {
7149                                    Slog.v(TAG, "Considering default browser match " + info);
7150                                }
7151                                defaultBrowserMatch = info;
7152                            }
7153                        }
7154                    }
7155                    if (defaultBrowserMatch != null
7156                            && defaultBrowserMatch.priority >= maxMatchPrio
7157                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7158                    {
7159                        if (debug) {
7160                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7161                        }
7162                        result.add(defaultBrowserMatch);
7163                    } else {
7164                        result.addAll(matchAllList);
7165                    }
7166                }
7167
7168                // If there is nothing selected, add all candidates and remove the ones that the user
7169                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7170                if (result.size() == 0) {
7171                    result.addAll(candidates);
7172                    result.removeAll(neverList);
7173                }
7174            }
7175        }
7176        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7177            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7178                    result.size());
7179            for (ResolveInfo info : result) {
7180                Slog.v(TAG, "  + " + info.activityInfo);
7181            }
7182        }
7183        return result;
7184    }
7185
7186    // Returns a packed value as a long:
7187    //
7188    // high 'int'-sized word: link status: undefined/ask/never/always.
7189    // low 'int'-sized word: relative priority among 'always' results.
7190    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7191        long result = ps.getDomainVerificationStatusForUser(userId);
7192        // if none available, get the master status
7193        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7194            if (ps.getIntentFilterVerificationInfo() != null) {
7195                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7196            }
7197        }
7198        return result;
7199    }
7200
7201    private ResolveInfo querySkipCurrentProfileIntents(
7202            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7203            int flags, int sourceUserId) {
7204        if (matchingFilters != null) {
7205            int size = matchingFilters.size();
7206            for (int i = 0; i < size; i ++) {
7207                CrossProfileIntentFilter filter = matchingFilters.get(i);
7208                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7209                    // Checking if there are activities in the target user that can handle the
7210                    // intent.
7211                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7212                            resolvedType, flags, sourceUserId);
7213                    if (resolveInfo != null) {
7214                        return resolveInfo;
7215                    }
7216                }
7217            }
7218        }
7219        return null;
7220    }
7221
7222    // Return matching ResolveInfo in target user if any.
7223    private ResolveInfo queryCrossProfileIntents(
7224            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7225            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7226        if (matchingFilters != null) {
7227            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7228            // match the same intent. For performance reasons, it is better not to
7229            // run queryIntent twice for the same userId
7230            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7231            int size = matchingFilters.size();
7232            for (int i = 0; i < size; i++) {
7233                CrossProfileIntentFilter filter = matchingFilters.get(i);
7234                int targetUserId = filter.getTargetUserId();
7235                boolean skipCurrentProfile =
7236                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7237                boolean skipCurrentProfileIfNoMatchFound =
7238                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7239                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7240                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7241                    // Checking if there are activities in the target user that can handle the
7242                    // intent.
7243                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7244                            resolvedType, flags, sourceUserId);
7245                    if (resolveInfo != null) return resolveInfo;
7246                    alreadyTriedUserIds.put(targetUserId, true);
7247                }
7248            }
7249        }
7250        return null;
7251    }
7252
7253    /**
7254     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7255     * will forward the intent to the filter's target user.
7256     * Otherwise, returns null.
7257     */
7258    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7259            String resolvedType, int flags, int sourceUserId) {
7260        int targetUserId = filter.getTargetUserId();
7261        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7262                resolvedType, flags, targetUserId);
7263        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7264            // If all the matches in the target profile are suspended, return null.
7265            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7266                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7267                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7268                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7269                            targetUserId);
7270                }
7271            }
7272        }
7273        return null;
7274    }
7275
7276    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7277            int sourceUserId, int targetUserId) {
7278        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7279        long ident = Binder.clearCallingIdentity();
7280        boolean targetIsProfile;
7281        try {
7282            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7283        } finally {
7284            Binder.restoreCallingIdentity(ident);
7285        }
7286        String className;
7287        if (targetIsProfile) {
7288            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7289        } else {
7290            className = FORWARD_INTENT_TO_PARENT;
7291        }
7292        ComponentName forwardingActivityComponentName = new ComponentName(
7293                mAndroidApplication.packageName, className);
7294        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7295                sourceUserId);
7296        if (!targetIsProfile) {
7297            forwardingActivityInfo.showUserIcon = targetUserId;
7298            forwardingResolveInfo.noResourceId = true;
7299        }
7300        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7301        forwardingResolveInfo.priority = 0;
7302        forwardingResolveInfo.preferredOrder = 0;
7303        forwardingResolveInfo.match = 0;
7304        forwardingResolveInfo.isDefault = true;
7305        forwardingResolveInfo.filter = filter;
7306        forwardingResolveInfo.targetUserId = targetUserId;
7307        return forwardingResolveInfo;
7308    }
7309
7310    @Override
7311    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7312            Intent[] specifics, String[] specificTypes, Intent intent,
7313            String resolvedType, int flags, int userId) {
7314        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7315                specificTypes, intent, resolvedType, flags, userId));
7316    }
7317
7318    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7319            Intent[] specifics, String[] specificTypes, Intent intent,
7320            String resolvedType, int flags, int userId) {
7321        if (!sUserManager.exists(userId)) return Collections.emptyList();
7322        final int callingUid = Binder.getCallingUid();
7323        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7324                false /*includeInstantApps*/);
7325        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7326                false /*requireFullPermission*/, false /*checkShell*/,
7327                "query intent activity options");
7328        final String resultsAction = intent.getAction();
7329
7330        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7331                | PackageManager.GET_RESOLVED_FILTER, userId);
7332
7333        if (DEBUG_INTENT_MATCHING) {
7334            Log.v(TAG, "Query " + intent + ": " + results);
7335        }
7336
7337        int specificsPos = 0;
7338        int N;
7339
7340        // todo: note that the algorithm used here is O(N^2).  This
7341        // isn't a problem in our current environment, but if we start running
7342        // into situations where we have more than 5 or 10 matches then this
7343        // should probably be changed to something smarter...
7344
7345        // First we go through and resolve each of the specific items
7346        // that were supplied, taking care of removing any corresponding
7347        // duplicate items in the generic resolve list.
7348        if (specifics != null) {
7349            for (int i=0; i<specifics.length; i++) {
7350                final Intent sintent = specifics[i];
7351                if (sintent == null) {
7352                    continue;
7353                }
7354
7355                if (DEBUG_INTENT_MATCHING) {
7356                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7357                }
7358
7359                String action = sintent.getAction();
7360                if (resultsAction != null && resultsAction.equals(action)) {
7361                    // If this action was explicitly requested, then don't
7362                    // remove things that have it.
7363                    action = null;
7364                }
7365
7366                ResolveInfo ri = null;
7367                ActivityInfo ai = null;
7368
7369                ComponentName comp = sintent.getComponent();
7370                if (comp == null) {
7371                    ri = resolveIntent(
7372                        sintent,
7373                        specificTypes != null ? specificTypes[i] : null,
7374                            flags, userId);
7375                    if (ri == null) {
7376                        continue;
7377                    }
7378                    if (ri == mResolveInfo) {
7379                        // ACK!  Must do something better with this.
7380                    }
7381                    ai = ri.activityInfo;
7382                    comp = new ComponentName(ai.applicationInfo.packageName,
7383                            ai.name);
7384                } else {
7385                    ai = getActivityInfo(comp, flags, userId);
7386                    if (ai == null) {
7387                        continue;
7388                    }
7389                }
7390
7391                // Look for any generic query activities that are duplicates
7392                // of this specific one, and remove them from the results.
7393                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7394                N = results.size();
7395                int j;
7396                for (j=specificsPos; j<N; j++) {
7397                    ResolveInfo sri = results.get(j);
7398                    if ((sri.activityInfo.name.equals(comp.getClassName())
7399                            && sri.activityInfo.applicationInfo.packageName.equals(
7400                                    comp.getPackageName()))
7401                        || (action != null && sri.filter.matchAction(action))) {
7402                        results.remove(j);
7403                        if (DEBUG_INTENT_MATCHING) Log.v(
7404                            TAG, "Removing duplicate item from " + j
7405                            + " due to specific " + specificsPos);
7406                        if (ri == null) {
7407                            ri = sri;
7408                        }
7409                        j--;
7410                        N--;
7411                    }
7412                }
7413
7414                // Add this specific item to its proper place.
7415                if (ri == null) {
7416                    ri = new ResolveInfo();
7417                    ri.activityInfo = ai;
7418                }
7419                results.add(specificsPos, ri);
7420                ri.specificIndex = i;
7421                specificsPos++;
7422            }
7423        }
7424
7425        // Now we go through the remaining generic results and remove any
7426        // duplicate actions that are found here.
7427        N = results.size();
7428        for (int i=specificsPos; i<N-1; i++) {
7429            final ResolveInfo rii = results.get(i);
7430            if (rii.filter == null) {
7431                continue;
7432            }
7433
7434            // Iterate over all of the actions of this result's intent
7435            // filter...  typically this should be just one.
7436            final Iterator<String> it = rii.filter.actionsIterator();
7437            if (it == null) {
7438                continue;
7439            }
7440            while (it.hasNext()) {
7441                final String action = it.next();
7442                if (resultsAction != null && resultsAction.equals(action)) {
7443                    // If this action was explicitly requested, then don't
7444                    // remove things that have it.
7445                    continue;
7446                }
7447                for (int j=i+1; j<N; j++) {
7448                    final ResolveInfo rij = results.get(j);
7449                    if (rij.filter != null && rij.filter.hasAction(action)) {
7450                        results.remove(j);
7451                        if (DEBUG_INTENT_MATCHING) Log.v(
7452                            TAG, "Removing duplicate item from " + j
7453                            + " due to action " + action + " at " + i);
7454                        j--;
7455                        N--;
7456                    }
7457                }
7458            }
7459
7460            // If the caller didn't request filter information, drop it now
7461            // so we don't have to marshall/unmarshall it.
7462            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7463                rii.filter = null;
7464            }
7465        }
7466
7467        // Filter out the caller activity if so requested.
7468        if (caller != null) {
7469            N = results.size();
7470            for (int i=0; i<N; i++) {
7471                ActivityInfo ainfo = results.get(i).activityInfo;
7472                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7473                        && caller.getClassName().equals(ainfo.name)) {
7474                    results.remove(i);
7475                    break;
7476                }
7477            }
7478        }
7479
7480        // If the caller didn't request filter information,
7481        // drop them now so we don't have to
7482        // marshall/unmarshall it.
7483        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7484            N = results.size();
7485            for (int i=0; i<N; i++) {
7486                results.get(i).filter = null;
7487            }
7488        }
7489
7490        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7491        return results;
7492    }
7493
7494    @Override
7495    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7496            String resolvedType, int flags, int userId) {
7497        return new ParceledListSlice<>(
7498                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7499                        false /*allowDynamicSplits*/));
7500    }
7501
7502    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7503            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7504        if (!sUserManager.exists(userId)) return Collections.emptyList();
7505        final int callingUid = Binder.getCallingUid();
7506        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7507                false /*requireFullPermission*/, false /*checkShell*/,
7508                "query intent receivers");
7509        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7510        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7511                false /*includeInstantApps*/);
7512        ComponentName comp = intent.getComponent();
7513        if (comp == null) {
7514            if (intent.getSelector() != null) {
7515                intent = intent.getSelector();
7516                comp = intent.getComponent();
7517            }
7518        }
7519        if (comp != null) {
7520            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7521            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7522            if (ai != null) {
7523                // When specifying an explicit component, we prevent the activity from being
7524                // used when either 1) the calling package is normal and the activity is within
7525                // an instant application or 2) the calling package is ephemeral and the
7526                // activity is not visible to instant applications.
7527                final boolean matchInstantApp =
7528                        (flags & PackageManager.MATCH_INSTANT) != 0;
7529                final boolean matchVisibleToInstantAppOnly =
7530                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7531                final boolean matchExplicitlyVisibleOnly =
7532                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7533                final boolean isCallerInstantApp =
7534                        instantAppPkgName != null;
7535                final boolean isTargetSameInstantApp =
7536                        comp.getPackageName().equals(instantAppPkgName);
7537                final boolean isTargetInstantApp =
7538                        (ai.applicationInfo.privateFlags
7539                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7540                final boolean isTargetVisibleToInstantApp =
7541                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7542                final boolean isTargetExplicitlyVisibleToInstantApp =
7543                        isTargetVisibleToInstantApp
7544                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7545                final boolean isTargetHiddenFromInstantApp =
7546                        !isTargetVisibleToInstantApp
7547                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7548                final boolean blockResolution =
7549                        !isTargetSameInstantApp
7550                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7551                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7552                                        && isTargetHiddenFromInstantApp));
7553                if (!blockResolution) {
7554                    ResolveInfo ri = new ResolveInfo();
7555                    ri.activityInfo = ai;
7556                    list.add(ri);
7557                }
7558            }
7559            return applyPostResolutionFilter(
7560                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7561        }
7562
7563        // reader
7564        synchronized (mPackages) {
7565            String pkgName = intent.getPackage();
7566            if (pkgName == null) {
7567                final List<ResolveInfo> result =
7568                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7569                return applyPostResolutionFilter(
7570                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7571            }
7572            final PackageParser.Package pkg = mPackages.get(pkgName);
7573            if (pkg != null) {
7574                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7575                        intent, resolvedType, flags, pkg.receivers, userId);
7576                return applyPostResolutionFilter(
7577                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7578            }
7579            return Collections.emptyList();
7580        }
7581    }
7582
7583    @Override
7584    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7585        final int callingUid = Binder.getCallingUid();
7586        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7587    }
7588
7589    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7590            int userId, int callingUid) {
7591        if (!sUserManager.exists(userId)) return null;
7592        flags = updateFlagsForResolve(
7593                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7594        List<ResolveInfo> query = queryIntentServicesInternal(
7595                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7596        if (query != null) {
7597            if (query.size() >= 1) {
7598                // If there is more than one service with the same priority,
7599                // just arbitrarily pick the first one.
7600                return query.get(0);
7601            }
7602        }
7603        return null;
7604    }
7605
7606    @Override
7607    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7608            String resolvedType, int flags, int userId) {
7609        final int callingUid = Binder.getCallingUid();
7610        return new ParceledListSlice<>(queryIntentServicesInternal(
7611                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7612    }
7613
7614    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7615            String resolvedType, int flags, int userId, int callingUid,
7616            boolean includeInstantApps) {
7617        if (!sUserManager.exists(userId)) return Collections.emptyList();
7618        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7619                false /*requireFullPermission*/, false /*checkShell*/,
7620                "query intent receivers");
7621        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7622        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7623        ComponentName comp = intent.getComponent();
7624        if (comp == null) {
7625            if (intent.getSelector() != null) {
7626                intent = intent.getSelector();
7627                comp = intent.getComponent();
7628            }
7629        }
7630        if (comp != null) {
7631            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7632            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7633            if (si != null) {
7634                // When specifying an explicit component, we prevent the service from being
7635                // used when either 1) the service is in an instant application and the
7636                // caller is not the same instant application or 2) the calling package is
7637                // ephemeral and the activity is not visible to ephemeral applications.
7638                final boolean matchInstantApp =
7639                        (flags & PackageManager.MATCH_INSTANT) != 0;
7640                final boolean matchVisibleToInstantAppOnly =
7641                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7642                final boolean isCallerInstantApp =
7643                        instantAppPkgName != null;
7644                final boolean isTargetSameInstantApp =
7645                        comp.getPackageName().equals(instantAppPkgName);
7646                final boolean isTargetInstantApp =
7647                        (si.applicationInfo.privateFlags
7648                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7649                final boolean isTargetHiddenFromInstantApp =
7650                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7651                final boolean blockResolution =
7652                        !isTargetSameInstantApp
7653                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7654                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7655                                        && isTargetHiddenFromInstantApp));
7656                if (!blockResolution) {
7657                    final ResolveInfo ri = new ResolveInfo();
7658                    ri.serviceInfo = si;
7659                    list.add(ri);
7660                }
7661            }
7662            return list;
7663        }
7664
7665        // reader
7666        synchronized (mPackages) {
7667            String pkgName = intent.getPackage();
7668            if (pkgName == null) {
7669                return applyPostServiceResolutionFilter(
7670                        mServices.queryIntent(intent, resolvedType, flags, userId),
7671                        instantAppPkgName);
7672            }
7673            final PackageParser.Package pkg = mPackages.get(pkgName);
7674            if (pkg != null) {
7675                return applyPostServiceResolutionFilter(
7676                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7677                                userId),
7678                        instantAppPkgName);
7679            }
7680            return Collections.emptyList();
7681        }
7682    }
7683
7684    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7685            String instantAppPkgName) {
7686        if (instantAppPkgName == null) {
7687            return resolveInfos;
7688        }
7689        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7690            final ResolveInfo info = resolveInfos.get(i);
7691            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7692            // allow services that are defined in the provided package
7693            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7694                if (info.serviceInfo.splitName != null
7695                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7696                                info.serviceInfo.splitName)) {
7697                    // requested service is defined in a split that hasn't been installed yet.
7698                    // add the installer to the resolve list
7699                    if (DEBUG_INSTANT) {
7700                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7701                    }
7702                    final ResolveInfo installerInfo = new ResolveInfo(
7703                            mInstantAppInstallerInfo);
7704                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7705                            null /* installFailureActivity */,
7706                            info.serviceInfo.packageName,
7707                            info.serviceInfo.applicationInfo.longVersionCode,
7708                            info.serviceInfo.splitName);
7709                    // add a non-generic filter
7710                    installerInfo.filter = new IntentFilter();
7711                    // load resources from the correct package
7712                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7713                    resolveInfos.set(i, installerInfo);
7714                }
7715                continue;
7716            }
7717            // allow services that have been explicitly exposed to ephemeral apps
7718            if (!isEphemeralApp
7719                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7720                continue;
7721            }
7722            resolveInfos.remove(i);
7723        }
7724        return resolveInfos;
7725    }
7726
7727    @Override
7728    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7729            String resolvedType, int flags, int userId) {
7730        return new ParceledListSlice<>(
7731                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7732    }
7733
7734    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7735            Intent intent, String resolvedType, int flags, int userId) {
7736        if (!sUserManager.exists(userId)) return Collections.emptyList();
7737        final int callingUid = Binder.getCallingUid();
7738        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7739        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7740                false /*includeInstantApps*/);
7741        ComponentName comp = intent.getComponent();
7742        if (comp == null) {
7743            if (intent.getSelector() != null) {
7744                intent = intent.getSelector();
7745                comp = intent.getComponent();
7746            }
7747        }
7748        if (comp != null) {
7749            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7750            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7751            if (pi != null) {
7752                // When specifying an explicit component, we prevent the provider from being
7753                // used when either 1) the provider is in an instant application and the
7754                // caller is not the same instant application or 2) the calling package is an
7755                // instant application and the provider is not visible to instant applications.
7756                final boolean matchInstantApp =
7757                        (flags & PackageManager.MATCH_INSTANT) != 0;
7758                final boolean matchVisibleToInstantAppOnly =
7759                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7760                final boolean isCallerInstantApp =
7761                        instantAppPkgName != null;
7762                final boolean isTargetSameInstantApp =
7763                        comp.getPackageName().equals(instantAppPkgName);
7764                final boolean isTargetInstantApp =
7765                        (pi.applicationInfo.privateFlags
7766                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7767                final boolean isTargetHiddenFromInstantApp =
7768                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7769                final boolean blockResolution =
7770                        !isTargetSameInstantApp
7771                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7772                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7773                                        && isTargetHiddenFromInstantApp));
7774                if (!blockResolution) {
7775                    final ResolveInfo ri = new ResolveInfo();
7776                    ri.providerInfo = pi;
7777                    list.add(ri);
7778                }
7779            }
7780            return list;
7781        }
7782
7783        // reader
7784        synchronized (mPackages) {
7785            String pkgName = intent.getPackage();
7786            if (pkgName == null) {
7787                return applyPostContentProviderResolutionFilter(
7788                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7789                        instantAppPkgName);
7790            }
7791            final PackageParser.Package pkg = mPackages.get(pkgName);
7792            if (pkg != null) {
7793                return applyPostContentProviderResolutionFilter(
7794                        mProviders.queryIntentForPackage(
7795                        intent, resolvedType, flags, pkg.providers, userId),
7796                        instantAppPkgName);
7797            }
7798            return Collections.emptyList();
7799        }
7800    }
7801
7802    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7803            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7804        if (instantAppPkgName == null) {
7805            return resolveInfos;
7806        }
7807        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7808            final ResolveInfo info = resolveInfos.get(i);
7809            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7810            // allow providers that are defined in the provided package
7811            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7812                if (info.providerInfo.splitName != null
7813                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7814                                info.providerInfo.splitName)) {
7815                    // requested provider is defined in a split that hasn't been installed yet.
7816                    // add the installer to the resolve list
7817                    if (DEBUG_INSTANT) {
7818                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7819                    }
7820                    final ResolveInfo installerInfo = new ResolveInfo(
7821                            mInstantAppInstallerInfo);
7822                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7823                            null /*failureActivity*/,
7824                            info.providerInfo.packageName,
7825                            info.providerInfo.applicationInfo.longVersionCode,
7826                            info.providerInfo.splitName);
7827                    // add a non-generic filter
7828                    installerInfo.filter = new IntentFilter();
7829                    // load resources from the correct package
7830                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7831                    resolveInfos.set(i, installerInfo);
7832                }
7833                continue;
7834            }
7835            // allow providers that have been explicitly exposed to instant applications
7836            if (!isEphemeralApp
7837                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7838                continue;
7839            }
7840            resolveInfos.remove(i);
7841        }
7842        return resolveInfos;
7843    }
7844
7845    @Override
7846    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7847        final int callingUid = Binder.getCallingUid();
7848        if (getInstantAppPackageName(callingUid) != null) {
7849            return ParceledListSlice.emptyList();
7850        }
7851        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7852        flags = updateFlagsForPackage(flags, userId, null);
7853        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7854        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7855                true /* requireFullPermission */, false /* checkShell */,
7856                "get installed packages");
7857
7858        // writer
7859        synchronized (mPackages) {
7860            ArrayList<PackageInfo> list;
7861            if (listUninstalled) {
7862                list = new ArrayList<>(mSettings.mPackages.size());
7863                for (PackageSetting ps : mSettings.mPackages.values()) {
7864                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7865                        continue;
7866                    }
7867                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7868                        continue;
7869                    }
7870                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7871                    if (pi != null) {
7872                        list.add(pi);
7873                    }
7874                }
7875            } else {
7876                list = new ArrayList<>(mPackages.size());
7877                for (PackageParser.Package p : mPackages.values()) {
7878                    final PackageSetting ps = (PackageSetting) p.mExtras;
7879                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7880                        continue;
7881                    }
7882                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7883                        continue;
7884                    }
7885                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7886                            p.mExtras, flags, userId);
7887                    if (pi != null) {
7888                        list.add(pi);
7889                    }
7890                }
7891            }
7892
7893            return new ParceledListSlice<>(list);
7894        }
7895    }
7896
7897    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7898            String[] permissions, boolean[] tmp, int flags, int userId) {
7899        int numMatch = 0;
7900        final PermissionsState permissionsState = ps.getPermissionsState();
7901        for (int i=0; i<permissions.length; i++) {
7902            final String permission = permissions[i];
7903            if (permissionsState.hasPermission(permission, userId)) {
7904                tmp[i] = true;
7905                numMatch++;
7906            } else {
7907                tmp[i] = false;
7908            }
7909        }
7910        if (numMatch == 0) {
7911            return;
7912        }
7913        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7914
7915        // The above might return null in cases of uninstalled apps or install-state
7916        // skew across users/profiles.
7917        if (pi != null) {
7918            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7919                if (numMatch == permissions.length) {
7920                    pi.requestedPermissions = permissions;
7921                } else {
7922                    pi.requestedPermissions = new String[numMatch];
7923                    numMatch = 0;
7924                    for (int i=0; i<permissions.length; i++) {
7925                        if (tmp[i]) {
7926                            pi.requestedPermissions[numMatch] = permissions[i];
7927                            numMatch++;
7928                        }
7929                    }
7930                }
7931            }
7932            list.add(pi);
7933        }
7934    }
7935
7936    @Override
7937    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7938            String[] permissions, int flags, int userId) {
7939        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7940        flags = updateFlagsForPackage(flags, userId, permissions);
7941        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7942                true /* requireFullPermission */, false /* checkShell */,
7943                "get packages holding permissions");
7944        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7945
7946        // writer
7947        synchronized (mPackages) {
7948            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7949            boolean[] tmpBools = new boolean[permissions.length];
7950            if (listUninstalled) {
7951                for (PackageSetting ps : mSettings.mPackages.values()) {
7952                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7953                            userId);
7954                }
7955            } else {
7956                for (PackageParser.Package pkg : mPackages.values()) {
7957                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7958                    if (ps != null) {
7959                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7960                                userId);
7961                    }
7962                }
7963            }
7964
7965            return new ParceledListSlice<PackageInfo>(list);
7966        }
7967    }
7968
7969    @Override
7970    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7971        final int callingUid = Binder.getCallingUid();
7972        if (getInstantAppPackageName(callingUid) != null) {
7973            return ParceledListSlice.emptyList();
7974        }
7975        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7976        flags = updateFlagsForApplication(flags, userId, null);
7977        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7978
7979        // writer
7980        synchronized (mPackages) {
7981            ArrayList<ApplicationInfo> list;
7982            if (listUninstalled) {
7983                list = new ArrayList<>(mSettings.mPackages.size());
7984                for (PackageSetting ps : mSettings.mPackages.values()) {
7985                    ApplicationInfo ai;
7986                    int effectiveFlags = flags;
7987                    if (ps.isSystem()) {
7988                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7989                    }
7990                    if (ps.pkg != null) {
7991                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7992                            continue;
7993                        }
7994                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7995                            continue;
7996                        }
7997                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7998                                ps.readUserState(userId), userId);
7999                        if (ai != null) {
8000                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8001                        }
8002                    } else {
8003                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8004                        // and already converts to externally visible package name
8005                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8006                                callingUid, effectiveFlags, userId);
8007                    }
8008                    if (ai != null) {
8009                        list.add(ai);
8010                    }
8011                }
8012            } else {
8013                list = new ArrayList<>(mPackages.size());
8014                for (PackageParser.Package p : mPackages.values()) {
8015                    if (p.mExtras != null) {
8016                        PackageSetting ps = (PackageSetting) p.mExtras;
8017                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8018                            continue;
8019                        }
8020                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8021                            continue;
8022                        }
8023                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8024                                ps.readUserState(userId), userId);
8025                        if (ai != null) {
8026                            ai.packageName = resolveExternalPackageNameLPr(p);
8027                            list.add(ai);
8028                        }
8029                    }
8030                }
8031            }
8032
8033            return new ParceledListSlice<>(list);
8034        }
8035    }
8036
8037    @Override
8038    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8039        if (HIDE_EPHEMERAL_APIS) {
8040            return null;
8041        }
8042        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8043            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8044                    "getEphemeralApplications");
8045        }
8046        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8047                true /* requireFullPermission */, false /* checkShell */,
8048                "getEphemeralApplications");
8049        synchronized (mPackages) {
8050            List<InstantAppInfo> instantApps = mInstantAppRegistry
8051                    .getInstantAppsLPr(userId);
8052            if (instantApps != null) {
8053                return new ParceledListSlice<>(instantApps);
8054            }
8055        }
8056        return null;
8057    }
8058
8059    @Override
8060    public boolean isInstantApp(String packageName, int userId) {
8061        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8062                true /* requireFullPermission */, false /* checkShell */,
8063                "isInstantApp");
8064        if (HIDE_EPHEMERAL_APIS) {
8065            return false;
8066        }
8067
8068        synchronized (mPackages) {
8069            int callingUid = Binder.getCallingUid();
8070            if (Process.isIsolated(callingUid)) {
8071                callingUid = mIsolatedOwners.get(callingUid);
8072            }
8073            final PackageSetting ps = mSettings.mPackages.get(packageName);
8074            PackageParser.Package pkg = mPackages.get(packageName);
8075            final boolean returnAllowed =
8076                    ps != null
8077                    && (isCallerSameApp(packageName, callingUid)
8078                            || canViewInstantApps(callingUid, userId)
8079                            || mInstantAppRegistry.isInstantAccessGranted(
8080                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8081            if (returnAllowed) {
8082                return ps.getInstantApp(userId);
8083            }
8084        }
8085        return false;
8086    }
8087
8088    @Override
8089    public byte[] getInstantAppCookie(String packageName, int userId) {
8090        if (HIDE_EPHEMERAL_APIS) {
8091            return null;
8092        }
8093
8094        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8095                true /* requireFullPermission */, false /* checkShell */,
8096                "getInstantAppCookie");
8097        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8098            return null;
8099        }
8100        synchronized (mPackages) {
8101            return mInstantAppRegistry.getInstantAppCookieLPw(
8102                    packageName, userId);
8103        }
8104    }
8105
8106    @Override
8107    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8108        if (HIDE_EPHEMERAL_APIS) {
8109            return true;
8110        }
8111
8112        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8113                true /* requireFullPermission */, true /* checkShell */,
8114                "setInstantAppCookie");
8115        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8116            return false;
8117        }
8118        synchronized (mPackages) {
8119            return mInstantAppRegistry.setInstantAppCookieLPw(
8120                    packageName, cookie, userId);
8121        }
8122    }
8123
8124    @Override
8125    public Bitmap getInstantAppIcon(String packageName, int userId) {
8126        if (HIDE_EPHEMERAL_APIS) {
8127            return null;
8128        }
8129
8130        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8131            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8132                    "getInstantAppIcon");
8133        }
8134        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8135                true /* requireFullPermission */, false /* checkShell */,
8136                "getInstantAppIcon");
8137
8138        synchronized (mPackages) {
8139            return mInstantAppRegistry.getInstantAppIconLPw(
8140                    packageName, userId);
8141        }
8142    }
8143
8144    private boolean isCallerSameApp(String packageName, int uid) {
8145        PackageParser.Package pkg = mPackages.get(packageName);
8146        return pkg != null
8147                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8148    }
8149
8150    @Override
8151    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8152        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8153            return ParceledListSlice.emptyList();
8154        }
8155        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8156    }
8157
8158    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8159        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8160
8161        // reader
8162        synchronized (mPackages) {
8163            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8164            final int userId = UserHandle.getCallingUserId();
8165            while (i.hasNext()) {
8166                final PackageParser.Package p = i.next();
8167                if (p.applicationInfo == null) continue;
8168
8169                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8170                        && !p.applicationInfo.isDirectBootAware();
8171                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8172                        && p.applicationInfo.isDirectBootAware();
8173
8174                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8175                        && (!mSafeMode || isSystemApp(p))
8176                        && (matchesUnaware || matchesAware)) {
8177                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8178                    if (ps != null) {
8179                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8180                                ps.readUserState(userId), userId);
8181                        if (ai != null) {
8182                            finalList.add(ai);
8183                        }
8184                    }
8185                }
8186            }
8187        }
8188
8189        return finalList;
8190    }
8191
8192    @Override
8193    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8194        return resolveContentProviderInternal(name, flags, userId);
8195    }
8196
8197    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8198        if (!sUserManager.exists(userId)) return null;
8199        flags = updateFlagsForComponent(flags, userId, name);
8200        final int callingUid = Binder.getCallingUid();
8201        synchronized (mPackages) {
8202            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8203            PackageSetting ps = provider != null
8204                    ? mSettings.mPackages.get(provider.owner.packageName)
8205                    : null;
8206            if (ps != null) {
8207                // provider not enabled
8208                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8209                    return null;
8210                }
8211                final ComponentName component =
8212                        new ComponentName(provider.info.packageName, provider.info.name);
8213                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8214                    return null;
8215                }
8216                return PackageParser.generateProviderInfo(
8217                        provider, flags, ps.readUserState(userId), userId);
8218            }
8219            return null;
8220        }
8221    }
8222
8223    /**
8224     * @deprecated
8225     */
8226    @Deprecated
8227    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8228        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8229            return;
8230        }
8231        // reader
8232        synchronized (mPackages) {
8233            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8234                    .entrySet().iterator();
8235            final int userId = UserHandle.getCallingUserId();
8236            while (i.hasNext()) {
8237                Map.Entry<String, PackageParser.Provider> entry = i.next();
8238                PackageParser.Provider p = entry.getValue();
8239                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8240
8241                if (ps != null && p.syncable
8242                        && (!mSafeMode || (p.info.applicationInfo.flags
8243                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8244                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8245                            ps.readUserState(userId), userId);
8246                    if (info != null) {
8247                        outNames.add(entry.getKey());
8248                        outInfo.add(info);
8249                    }
8250                }
8251            }
8252        }
8253    }
8254
8255    @Override
8256    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8257            int uid, int flags, String metaDataKey) {
8258        final int callingUid = Binder.getCallingUid();
8259        final int userId = processName != null ? UserHandle.getUserId(uid)
8260                : UserHandle.getCallingUserId();
8261        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8262        flags = updateFlagsForComponent(flags, userId, processName);
8263        ArrayList<ProviderInfo> finalList = null;
8264        // reader
8265        synchronized (mPackages) {
8266            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8267            while (i.hasNext()) {
8268                final PackageParser.Provider p = i.next();
8269                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8270                if (ps != null && p.info.authority != null
8271                        && (processName == null
8272                                || (p.info.processName.equals(processName)
8273                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8274                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8275
8276                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8277                    // parameter.
8278                    if (metaDataKey != null
8279                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8280                        continue;
8281                    }
8282                    final ComponentName component =
8283                            new ComponentName(p.info.packageName, p.info.name);
8284                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8285                        continue;
8286                    }
8287                    if (finalList == null) {
8288                        finalList = new ArrayList<ProviderInfo>(3);
8289                    }
8290                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8291                            ps.readUserState(userId), userId);
8292                    if (info != null) {
8293                        finalList.add(info);
8294                    }
8295                }
8296            }
8297        }
8298
8299        if (finalList != null) {
8300            Collections.sort(finalList, mProviderInitOrderSorter);
8301            return new ParceledListSlice<ProviderInfo>(finalList);
8302        }
8303
8304        return ParceledListSlice.emptyList();
8305    }
8306
8307    @Override
8308    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8309        // reader
8310        synchronized (mPackages) {
8311            final int callingUid = Binder.getCallingUid();
8312            final int callingUserId = UserHandle.getUserId(callingUid);
8313            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8314            if (ps == null) return null;
8315            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8316                return null;
8317            }
8318            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8319            return PackageParser.generateInstrumentationInfo(i, flags);
8320        }
8321    }
8322
8323    @Override
8324    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8325            String targetPackage, int flags) {
8326        final int callingUid = Binder.getCallingUid();
8327        final int callingUserId = UserHandle.getUserId(callingUid);
8328        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8329        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8330            return ParceledListSlice.emptyList();
8331        }
8332        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8333    }
8334
8335    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8336            int flags) {
8337        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8338
8339        // reader
8340        synchronized (mPackages) {
8341            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8342            while (i.hasNext()) {
8343                final PackageParser.Instrumentation p = i.next();
8344                if (targetPackage == null
8345                        || targetPackage.equals(p.info.targetPackage)) {
8346                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8347                            flags);
8348                    if (ii != null) {
8349                        finalList.add(ii);
8350                    }
8351                }
8352            }
8353        }
8354
8355        return finalList;
8356    }
8357
8358    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8359        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8360        try {
8361            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8362        } finally {
8363            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8364        }
8365    }
8366
8367    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8368        final File[] files = scanDir.listFiles();
8369        if (ArrayUtils.isEmpty(files)) {
8370            Log.d(TAG, "No files in app dir " + scanDir);
8371            return;
8372        }
8373
8374        if (DEBUG_PACKAGE_SCANNING) {
8375            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8376                    + " flags=0x" + Integer.toHexString(parseFlags));
8377        }
8378        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8379                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8380                mParallelPackageParserCallback)) {
8381            // Submit files for parsing in parallel
8382            int fileCount = 0;
8383            for (File file : files) {
8384                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8385                        && !PackageInstallerService.isStageName(file.getName());
8386                if (!isPackage) {
8387                    // Ignore entries which are not packages
8388                    continue;
8389                }
8390                parallelPackageParser.submit(file, parseFlags);
8391                fileCount++;
8392            }
8393
8394            // Process results one by one
8395            for (; fileCount > 0; fileCount--) {
8396                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8397                Throwable throwable = parseResult.throwable;
8398                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8399
8400                if (throwable == null) {
8401                    // TODO(toddke): move lower in the scan chain
8402                    // Static shared libraries have synthetic package names
8403                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8404                        renameStaticSharedLibraryPackage(parseResult.pkg);
8405                    }
8406                    try {
8407                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8408                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8409                                    currentTime, null);
8410                        }
8411                    } catch (PackageManagerException e) {
8412                        errorCode = e.error;
8413                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8414                    }
8415                } else if (throwable instanceof PackageParser.PackageParserException) {
8416                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8417                            throwable;
8418                    errorCode = e.error;
8419                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8420                } else {
8421                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8422                            + parseResult.scanFile, throwable);
8423                }
8424
8425                // Delete invalid userdata apps
8426                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8427                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8428                    logCriticalInfo(Log.WARN,
8429                            "Deleting invalid package at " + parseResult.scanFile);
8430                    removeCodePathLI(parseResult.scanFile);
8431                }
8432            }
8433        }
8434    }
8435
8436    public static void reportSettingsProblem(int priority, String msg) {
8437        logCriticalInfo(priority, msg);
8438    }
8439
8440    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8441            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8442        // When upgrading from pre-N MR1, verify the package time stamp using the package
8443        // directory and not the APK file.
8444        final long lastModifiedTime = mIsPreNMR1Upgrade
8445                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8446        if (ps != null && !forceCollect
8447                && ps.codePathString.equals(pkg.codePath)
8448                && ps.timeStamp == lastModifiedTime
8449                && !isCompatSignatureUpdateNeeded(pkg)
8450                && !isRecoverSignatureUpdateNeeded(pkg)) {
8451            if (ps.signatures.mSigningDetails.signatures != null
8452                    && ps.signatures.mSigningDetails.signatures.length != 0
8453                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8454                            != SignatureSchemeVersion.UNKNOWN) {
8455                // Optimization: reuse the existing cached signing data
8456                // if the package appears to be unchanged.
8457                pkg.mSigningDetails =
8458                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8459                return;
8460            }
8461
8462            Slog.w(TAG, "PackageSetting for " + ps.name
8463                    + " is missing signatures.  Collecting certs again to recover them.");
8464        } else {
8465            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8466                    (forceCollect ? " (forced)" : ""));
8467        }
8468
8469        try {
8470            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8471            PackageParser.collectCertificates(pkg, skipVerify);
8472        } catch (PackageParserException e) {
8473            throw PackageManagerException.from(e);
8474        } finally {
8475            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8476        }
8477    }
8478
8479    /**
8480     *  Traces a package scan.
8481     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8482     */
8483    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8484            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8485        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8486        try {
8487            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8488        } finally {
8489            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8490        }
8491    }
8492
8493    /**
8494     *  Scans a package and returns the newly parsed package.
8495     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8496     */
8497    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8498            long currentTime, UserHandle user) throws PackageManagerException {
8499        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8500        PackageParser pp = new PackageParser();
8501        pp.setSeparateProcesses(mSeparateProcesses);
8502        pp.setOnlyCoreApps(mOnlyCore);
8503        pp.setDisplayMetrics(mMetrics);
8504        pp.setCallback(mPackageParserCallback);
8505
8506        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8507        final PackageParser.Package pkg;
8508        try {
8509            pkg = pp.parsePackage(scanFile, parseFlags);
8510        } catch (PackageParserException e) {
8511            throw PackageManagerException.from(e);
8512        } finally {
8513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8514        }
8515
8516        // Static shared libraries have synthetic package names
8517        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8518            renameStaticSharedLibraryPackage(pkg);
8519        }
8520
8521        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8522    }
8523
8524    /**
8525     *  Scans a package and returns the newly parsed package.
8526     *  @throws PackageManagerException on a parse error.
8527     */
8528    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8529            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8530            @Nullable UserHandle user)
8531                    throws PackageManagerException {
8532        // If the package has children and this is the first dive in the function
8533        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8534        // packages (parent and children) would be successfully scanned before the
8535        // actual scan since scanning mutates internal state and we want to atomically
8536        // install the package and its children.
8537        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8538            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8539                scanFlags |= SCAN_CHECK_ONLY;
8540            }
8541        } else {
8542            scanFlags &= ~SCAN_CHECK_ONLY;
8543        }
8544
8545        // Scan the parent
8546        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8547                scanFlags, currentTime, user);
8548
8549        // Scan the children
8550        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8551        for (int i = 0; i < childCount; i++) {
8552            PackageParser.Package childPackage = pkg.childPackages.get(i);
8553            addForInitLI(childPackage, parseFlags, scanFlags,
8554                    currentTime, user);
8555        }
8556
8557
8558        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8559            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8560        }
8561
8562        return scannedPkg;
8563    }
8564
8565    /**
8566     * Returns if full apk verification can be skipped for the whole package, including the splits.
8567     */
8568    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8569        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8570            return false;
8571        }
8572        // TODO: Allow base and splits to be verified individually.
8573        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8574            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8575                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8576                    return false;
8577                }
8578            }
8579        }
8580        return true;
8581    }
8582
8583    /**
8584     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8585     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8586     * match one in a trusted source, and should be done separately.
8587     */
8588    private boolean canSkipFullApkVerification(String apkPath) {
8589        byte[] rootHashObserved = null;
8590        try {
8591            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8592            if (rootHashObserved == null) {
8593                return false;  // APK does not contain Merkle tree root hash.
8594            }
8595            synchronized (mInstallLock) {
8596                // Returns whether the observed root hash matches what kernel has.
8597                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8598                return true;
8599            }
8600        } catch (InstallerException | IOException | DigestException |
8601                NoSuchAlgorithmException e) {
8602            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8603        }
8604        return false;
8605    }
8606
8607    /**
8608     * Adds a new package to the internal data structures during platform initialization.
8609     * <p>After adding, the package is known to the system and available for querying.
8610     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8611     * etc...], additional checks are performed. Basic verification [such as ensuring
8612     * matching signatures, checking version codes, etc...] occurs if the package is
8613     * identical to a previously known package. If the package fails a signature check,
8614     * the version installed on /data will be removed. If the version of the new package
8615     * is less than or equal than the version on /data, it will be ignored.
8616     * <p>Regardless of the package location, the results are applied to the internal
8617     * structures and the package is made available to the rest of the system.
8618     * <p>NOTE: The return value should be removed. It's the passed in package object.
8619     */
8620    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8621            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8622            @Nullable UserHandle user)
8623                    throws PackageManagerException {
8624        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8625        final String renamedPkgName;
8626        final PackageSetting disabledPkgSetting;
8627        final boolean isSystemPkgUpdated;
8628        final boolean pkgAlreadyExists;
8629        PackageSetting pkgSetting;
8630
8631        // NOTE: installPackageLI() has the same code to setup the package's
8632        // application info. This probably should be done lower in the call
8633        // stack [such as scanPackageOnly()]. However, we verify the application
8634        // info prior to that [in scanPackageNew()] and thus have to setup
8635        // the application info early.
8636        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8637        pkg.setApplicationInfoCodePath(pkg.codePath);
8638        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8639        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8640        pkg.setApplicationInfoResourcePath(pkg.codePath);
8641        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8642        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8643
8644        synchronized (mPackages) {
8645            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8646            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8647            if (realPkgName != null) {
8648                ensurePackageRenamed(pkg, renamedPkgName);
8649            }
8650            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8651            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8652            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8653            pkgAlreadyExists = pkgSetting != null;
8654            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8655            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8656            isSystemPkgUpdated = disabledPkgSetting != null;
8657
8658            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8659                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8660            }
8661
8662            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8663                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8664                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8665                    : null;
8666            if (DEBUG_PACKAGE_SCANNING
8667                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8668                    && sharedUserSetting != null) {
8669                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8670                        + " (uid=" + sharedUserSetting.userId + "):"
8671                        + " packages=" + sharedUserSetting.packages);
8672            }
8673
8674            if (scanSystemPartition) {
8675                // Potentially prune child packages. If the application on the /system
8676                // partition has been updated via OTA, but, is still disabled by a
8677                // version on /data, cycle through all of its children packages and
8678                // remove children that are no longer defined.
8679                if (isSystemPkgUpdated) {
8680                    final int scannedChildCount = (pkg.childPackages != null)
8681                            ? pkg.childPackages.size() : 0;
8682                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8683                            ? disabledPkgSetting.childPackageNames.size() : 0;
8684                    for (int i = 0; i < disabledChildCount; i++) {
8685                        String disabledChildPackageName =
8686                                disabledPkgSetting.childPackageNames.get(i);
8687                        boolean disabledPackageAvailable = false;
8688                        for (int j = 0; j < scannedChildCount; j++) {
8689                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8690                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8691                                disabledPackageAvailable = true;
8692                                break;
8693                            }
8694                        }
8695                        if (!disabledPackageAvailable) {
8696                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8697                        }
8698                    }
8699                    // we're updating the disabled package, so, scan it as the package setting
8700                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8701                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8702                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8703                            (pkg == mPlatformPackage), user);
8704                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8705                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8706                }
8707            }
8708        }
8709
8710        final boolean newPkgChangedPaths =
8711                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8712        final boolean newPkgVersionGreater =
8713                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8714        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8715                && newPkgChangedPaths && newPkgVersionGreater;
8716        if (isSystemPkgBetter) {
8717            // The version of the application on /system is greater than the version on
8718            // /data. Switch back to the application on /system.
8719            // It's safe to assume the application on /system will correctly scan. If not,
8720            // there won't be a working copy of the application.
8721            synchronized (mPackages) {
8722                // just remove the loaded entries from package lists
8723                mPackages.remove(pkgSetting.name);
8724            }
8725
8726            logCriticalInfo(Log.WARN,
8727                    "System package updated;"
8728                    + " name: " + pkgSetting.name
8729                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8730                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8731
8732            final InstallArgs args = createInstallArgsForExisting(
8733                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8734                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8735            args.cleanUpResourcesLI();
8736            synchronized (mPackages) {
8737                mSettings.enableSystemPackageLPw(pkgSetting.name);
8738            }
8739        }
8740
8741        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8742            // The version of the application on the /system partition is less than or
8743            // equal to the version on the /data partition. Throw an exception and use
8744            // the application already installed on the /data partition.
8745            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8746                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8747                    + " better than this " + pkg.getLongVersionCode());
8748        }
8749
8750        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8751        // force re-collecting certificate.
8752        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8753                disabledPkgSetting);
8754        // Full APK verification can be skipped during certificate collection, only if the file is
8755        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8756        // cases, only data in Signing Block is verified instead of the whole file.
8757        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8758                (forceCollect && canSkipFullPackageVerification(pkg));
8759        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8760
8761        boolean shouldHideSystemApp = false;
8762        // A new application appeared on /system, but, we already have a copy of
8763        // the application installed on /data.
8764        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8765                && !pkgSetting.isSystem()) {
8766
8767            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8768                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8769                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8770                                    pkg.mSigningDetails,
8771                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8772                logCriticalInfo(Log.WARN,
8773                        "System package signature mismatch;"
8774                        + " name: " + pkgSetting.name);
8775                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8776                        "scanPackageInternalLI")) {
8777                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8778                }
8779                pkgSetting = null;
8780            } else if (newPkgVersionGreater) {
8781                // The application on /system is newer than the application on /data.
8782                // Simply remove the application on /data [keeping application data]
8783                // and replace it with the version on /system.
8784                logCriticalInfo(Log.WARN,
8785                        "System package enabled;"
8786                        + " name: " + pkgSetting.name
8787                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8788                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8789                InstallArgs args = createInstallArgsForExisting(
8790                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8791                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8792                synchronized (mInstallLock) {
8793                    args.cleanUpResourcesLI();
8794                }
8795            } else {
8796                // The application on /system is older than the application on /data. Hide
8797                // the application on /system and the version on /data will be scanned later
8798                // and re-added like an update.
8799                shouldHideSystemApp = true;
8800                logCriticalInfo(Log.INFO,
8801                        "System package disabled;"
8802                        + " name: " + pkgSetting.name
8803                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8804                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8805            }
8806        }
8807
8808        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8809                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8810
8811        if (shouldHideSystemApp) {
8812            synchronized (mPackages) {
8813                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8814            }
8815        }
8816        return scannedPkg;
8817    }
8818
8819    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8820        // Derive the new package synthetic package name
8821        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8822                + pkg.staticSharedLibVersion);
8823    }
8824
8825    private static String fixProcessName(String defProcessName,
8826            String processName) {
8827        if (processName == null) {
8828            return defProcessName;
8829        }
8830        return processName;
8831    }
8832
8833    /**
8834     * Enforces that only the system UID or root's UID can call a method exposed
8835     * via Binder.
8836     *
8837     * @param message used as message if SecurityException is thrown
8838     * @throws SecurityException if the caller is not system or root
8839     */
8840    private static final void enforceSystemOrRoot(String message) {
8841        final int uid = Binder.getCallingUid();
8842        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8843            throw new SecurityException(message);
8844        }
8845    }
8846
8847    @Override
8848    public void performFstrimIfNeeded() {
8849        enforceSystemOrRoot("Only the system can request fstrim");
8850
8851        // Before everything else, see whether we need to fstrim.
8852        try {
8853            IStorageManager sm = PackageHelper.getStorageManager();
8854            if (sm != null) {
8855                boolean doTrim = false;
8856                final long interval = android.provider.Settings.Global.getLong(
8857                        mContext.getContentResolver(),
8858                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8859                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8860                if (interval > 0) {
8861                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8862                    if (timeSinceLast > interval) {
8863                        doTrim = true;
8864                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8865                                + "; running immediately");
8866                    }
8867                }
8868                if (doTrim) {
8869                    final boolean dexOptDialogShown;
8870                    synchronized (mPackages) {
8871                        dexOptDialogShown = mDexOptDialogShown;
8872                    }
8873                    if (!isFirstBoot() && dexOptDialogShown) {
8874                        try {
8875                            ActivityManager.getService().showBootMessage(
8876                                    mContext.getResources().getString(
8877                                            R.string.android_upgrading_fstrim), true);
8878                        } catch (RemoteException e) {
8879                        }
8880                    }
8881                    sm.runMaintenance();
8882                }
8883            } else {
8884                Slog.e(TAG, "storageManager service unavailable!");
8885            }
8886        } catch (RemoteException e) {
8887            // Can't happen; StorageManagerService is local
8888        }
8889    }
8890
8891    @Override
8892    public void updatePackagesIfNeeded() {
8893        enforceSystemOrRoot("Only the system can request package update");
8894
8895        // We need to re-extract after an OTA.
8896        boolean causeUpgrade = isUpgrade();
8897
8898        // First boot or factory reset.
8899        // Note: we also handle devices that are upgrading to N right now as if it is their
8900        //       first boot, as they do not have profile data.
8901        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8902
8903        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8904        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8905
8906        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8907            return;
8908        }
8909
8910        List<PackageParser.Package> pkgs;
8911        synchronized (mPackages) {
8912            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8913        }
8914
8915        final long startTime = System.nanoTime();
8916        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8917                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8918                    false /* bootComplete */);
8919
8920        final int elapsedTimeSeconds =
8921                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8922
8923        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8924        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8925        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8926        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8927        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8928    }
8929
8930    /*
8931     * Return the prebuilt profile path given a package base code path.
8932     */
8933    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8934        return pkg.baseCodePath + ".prof";
8935    }
8936
8937    /**
8938     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8939     * containing statistics about the invocation. The array consists of three elements,
8940     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8941     * and {@code numberOfPackagesFailed}.
8942     */
8943    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8944            final int compilationReason, boolean bootComplete) {
8945
8946        int numberOfPackagesVisited = 0;
8947        int numberOfPackagesOptimized = 0;
8948        int numberOfPackagesSkipped = 0;
8949        int numberOfPackagesFailed = 0;
8950        final int numberOfPackagesToDexopt = pkgs.size();
8951
8952        for (PackageParser.Package pkg : pkgs) {
8953            numberOfPackagesVisited++;
8954
8955            boolean useProfileForDexopt = false;
8956
8957            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8958                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8959                // that are already compiled.
8960                File profileFile = new File(getPrebuildProfilePath(pkg));
8961                // Copy profile if it exists.
8962                if (profileFile.exists()) {
8963                    try {
8964                        // We could also do this lazily before calling dexopt in
8965                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8966                        // is that we don't have a good way to say "do this only once".
8967                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8968                                pkg.applicationInfo.uid, pkg.packageName,
8969                                ArtManager.getProfileName(null))) {
8970                            Log.e(TAG, "Installer failed to copy system profile!");
8971                        } else {
8972                            // Disabled as this causes speed-profile compilation during first boot
8973                            // even if things are already compiled.
8974                            // useProfileForDexopt = true;
8975                        }
8976                    } catch (Exception e) {
8977                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8978                                e);
8979                    }
8980                } else {
8981                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8982                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8983                    // minimize the number off apps being speed-profile compiled during first boot.
8984                    // The other paths will not change the filter.
8985                    if (disabledPs != null && disabledPs.pkg.isStub) {
8986                        // The package is the stub one, remove the stub suffix to get the normal
8987                        // package and APK names.
8988                        String systemProfilePath =
8989                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8990                        profileFile = new File(systemProfilePath);
8991                        // If we have a profile for a compressed APK, copy it to the reference
8992                        // location.
8993                        // Note that copying the profile here will cause it to override the
8994                        // reference profile every OTA even though the existing reference profile
8995                        // may have more data. We can't copy during decompression since the
8996                        // directories are not set up at that point.
8997                        if (profileFile.exists()) {
8998                            try {
8999                                // We could also do this lazily before calling dexopt in
9000                                // PackageDexOptimizer to prevent this happening on first boot. The
9001                                // issue is that we don't have a good way to say "do this only
9002                                // once".
9003                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9004                                        pkg.applicationInfo.uid, pkg.packageName,
9005                                        ArtManager.getProfileName(null))) {
9006                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9007                                } else {
9008                                    useProfileForDexopt = true;
9009                                }
9010                            } catch (Exception e) {
9011                                Log.e(TAG, "Failed to copy profile " +
9012                                        profileFile.getAbsolutePath() + " ", e);
9013                            }
9014                        }
9015                    }
9016                }
9017            }
9018
9019            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9020                if (DEBUG_DEXOPT) {
9021                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9022                }
9023                numberOfPackagesSkipped++;
9024                continue;
9025            }
9026
9027            if (DEBUG_DEXOPT) {
9028                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9029                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9030            }
9031
9032            if (showDialog) {
9033                try {
9034                    ActivityManager.getService().showBootMessage(
9035                            mContext.getResources().getString(R.string.android_upgrading_apk,
9036                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9037                } catch (RemoteException e) {
9038                }
9039                synchronized (mPackages) {
9040                    mDexOptDialogShown = true;
9041                }
9042            }
9043
9044            int pkgCompilationReason = compilationReason;
9045            if (useProfileForDexopt) {
9046                // Use background dexopt mode to try and use the profile. Note that this does not
9047                // guarantee usage of the profile.
9048                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9049            }
9050
9051            // checkProfiles is false to avoid merging profiles during boot which
9052            // might interfere with background compilation (b/28612421).
9053            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9054            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9055            // trade-off worth doing to save boot time work.
9056            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9057            if (compilationReason == REASON_FIRST_BOOT) {
9058                // TODO: This doesn't cover the upgrade case, we should check for this too.
9059                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9060            }
9061            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9062                    pkg.packageName,
9063                    pkgCompilationReason,
9064                    dexoptFlags));
9065
9066            switch (primaryDexOptStaus) {
9067                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9068                    numberOfPackagesOptimized++;
9069                    break;
9070                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9071                    numberOfPackagesSkipped++;
9072                    break;
9073                case PackageDexOptimizer.DEX_OPT_FAILED:
9074                    numberOfPackagesFailed++;
9075                    break;
9076                default:
9077                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9078                    break;
9079            }
9080        }
9081
9082        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9083                numberOfPackagesFailed };
9084    }
9085
9086    @Override
9087    public void notifyPackageUse(String packageName, int reason) {
9088        synchronized (mPackages) {
9089            final int callingUid = Binder.getCallingUid();
9090            final int callingUserId = UserHandle.getUserId(callingUid);
9091            if (getInstantAppPackageName(callingUid) != null) {
9092                if (!isCallerSameApp(packageName, callingUid)) {
9093                    return;
9094                }
9095            } else {
9096                if (isInstantApp(packageName, callingUserId)) {
9097                    return;
9098                }
9099            }
9100            notifyPackageUseLocked(packageName, reason);
9101        }
9102    }
9103
9104    @GuardedBy("mPackages")
9105    private void notifyPackageUseLocked(String packageName, int reason) {
9106        final PackageParser.Package p = mPackages.get(packageName);
9107        if (p == null) {
9108            return;
9109        }
9110        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9111    }
9112
9113    @Override
9114    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9115            List<String> classPaths, String loaderIsa) {
9116        int userId = UserHandle.getCallingUserId();
9117        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9118        if (ai == null) {
9119            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9120                + loadingPackageName + ", user=" + userId);
9121            return;
9122        }
9123        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9124    }
9125
9126    @Override
9127    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9128            IDexModuleRegisterCallback callback) {
9129        int userId = UserHandle.getCallingUserId();
9130        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9131        DexManager.RegisterDexModuleResult result;
9132        if (ai == null) {
9133            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9134                     " calling user. package=" + packageName + ", user=" + userId);
9135            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9136        } else {
9137            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9138        }
9139
9140        if (callback != null) {
9141            mHandler.post(() -> {
9142                try {
9143                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9144                } catch (RemoteException e) {
9145                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9146                }
9147            });
9148        }
9149    }
9150
9151    /**
9152     * Ask the package manager to perform a dex-opt with the given compiler filter.
9153     *
9154     * Note: exposed only for the shell command to allow moving packages explicitly to a
9155     *       definite state.
9156     */
9157    @Override
9158    public boolean performDexOptMode(String packageName,
9159            boolean checkProfiles, String targetCompilerFilter, boolean force,
9160            boolean bootComplete, String splitName) {
9161        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9162                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9163                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9164        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9165                targetCompilerFilter, splitName, flags));
9166    }
9167
9168    /**
9169     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9170     * secondary dex files belonging to the given package.
9171     *
9172     * Note: exposed only for the shell command to allow moving packages explicitly to a
9173     *       definite state.
9174     */
9175    @Override
9176    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9177            boolean force) {
9178        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9179                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9180                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9181                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9182        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9183    }
9184
9185    /*package*/ boolean performDexOpt(DexoptOptions options) {
9186        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9187            return false;
9188        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9189            return false;
9190        }
9191
9192        if (options.isDexoptOnlySecondaryDex()) {
9193            return mDexManager.dexoptSecondaryDex(options);
9194        } else {
9195            int dexoptStatus = performDexOptWithStatus(options);
9196            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9197        }
9198    }
9199
9200    /**
9201     * Perform dexopt on the given package and return one of following result:
9202     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9203     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9204     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9205     */
9206    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9207        return performDexOptTraced(options);
9208    }
9209
9210    private int performDexOptTraced(DexoptOptions options) {
9211        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9212        try {
9213            return performDexOptInternal(options);
9214        } finally {
9215            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9216        }
9217    }
9218
9219    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9220    // if the package can now be considered up to date for the given filter.
9221    private int performDexOptInternal(DexoptOptions options) {
9222        PackageParser.Package p;
9223        synchronized (mPackages) {
9224            p = mPackages.get(options.getPackageName());
9225            if (p == null) {
9226                // Package could not be found. Report failure.
9227                return PackageDexOptimizer.DEX_OPT_FAILED;
9228            }
9229            mPackageUsage.maybeWriteAsync(mPackages);
9230            mCompilerStats.maybeWriteAsync();
9231        }
9232        long callingId = Binder.clearCallingIdentity();
9233        try {
9234            synchronized (mInstallLock) {
9235                return performDexOptInternalWithDependenciesLI(p, options);
9236            }
9237        } finally {
9238            Binder.restoreCallingIdentity(callingId);
9239        }
9240    }
9241
9242    public ArraySet<String> getOptimizablePackages() {
9243        ArraySet<String> pkgs = new ArraySet<String>();
9244        synchronized (mPackages) {
9245            for (PackageParser.Package p : mPackages.values()) {
9246                if (PackageDexOptimizer.canOptimizePackage(p)) {
9247                    pkgs.add(p.packageName);
9248                }
9249            }
9250        }
9251        return pkgs;
9252    }
9253
9254    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9255            DexoptOptions options) {
9256        // Select the dex optimizer based on the force parameter.
9257        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9258        //       allocate an object here.
9259        PackageDexOptimizer pdo = options.isForce()
9260                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9261                : mPackageDexOptimizer;
9262
9263        // Dexopt all dependencies first. Note: we ignore the return value and march on
9264        // on errors.
9265        // Note that we are going to call performDexOpt on those libraries as many times as
9266        // they are referenced in packages. When we do a batch of performDexOpt (for example
9267        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9268        // and the first package that uses the library will dexopt it. The
9269        // others will see that the compiled code for the library is up to date.
9270        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9271        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9272        if (!deps.isEmpty()) {
9273            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9274                    options.getCompilationReason(), options.getCompilerFilter(),
9275                    options.getSplitName(),
9276                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9277            for (PackageParser.Package depPackage : deps) {
9278                // TODO: Analyze and investigate if we (should) profile libraries.
9279                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9280                        getOrCreateCompilerPackageStats(depPackage),
9281                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9282            }
9283        }
9284        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9285                getOrCreateCompilerPackageStats(p),
9286                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9287    }
9288
9289    /**
9290     * Reconcile the information we have about the secondary dex files belonging to
9291     * {@code packagName} and the actual dex files. For all dex files that were
9292     * deleted, update the internal records and delete the generated oat files.
9293     */
9294    @Override
9295    public void reconcileSecondaryDexFiles(String packageName) {
9296        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9297            return;
9298        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9299            return;
9300        }
9301        mDexManager.reconcileSecondaryDexFiles(packageName);
9302    }
9303
9304    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9305    // a reference there.
9306    /*package*/ DexManager getDexManager() {
9307        return mDexManager;
9308    }
9309
9310    /**
9311     * Execute the background dexopt job immediately.
9312     */
9313    @Override
9314    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9315        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9316            return false;
9317        }
9318        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9319    }
9320
9321    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9322        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9323                || p.usesStaticLibraries != null) {
9324            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9325            Set<String> collectedNames = new HashSet<>();
9326            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9327
9328            retValue.remove(p);
9329
9330            return retValue;
9331        } else {
9332            return Collections.emptyList();
9333        }
9334    }
9335
9336    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9337            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9338        if (!collectedNames.contains(p.packageName)) {
9339            collectedNames.add(p.packageName);
9340            collected.add(p);
9341
9342            if (p.usesLibraries != null) {
9343                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9344                        null, collected, collectedNames);
9345            }
9346            if (p.usesOptionalLibraries != null) {
9347                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9348                        null, collected, collectedNames);
9349            }
9350            if (p.usesStaticLibraries != null) {
9351                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9352                        p.usesStaticLibrariesVersions, collected, collectedNames);
9353            }
9354        }
9355    }
9356
9357    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9358            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9359        final int libNameCount = libs.size();
9360        for (int i = 0; i < libNameCount; i++) {
9361            String libName = libs.get(i);
9362            long version = (versions != null && versions.length == libNameCount)
9363                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9364            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9365            if (libPkg != null) {
9366                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9367            }
9368        }
9369    }
9370
9371    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9372        synchronized (mPackages) {
9373            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9374            if (libEntry != null) {
9375                return mPackages.get(libEntry.apk);
9376            }
9377            return null;
9378        }
9379    }
9380
9381    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9382        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9383        if (versionedLib == null) {
9384            return null;
9385        }
9386        return versionedLib.get(version);
9387    }
9388
9389    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9390        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9391                pkg.staticSharedLibName);
9392        if (versionedLib == null) {
9393            return null;
9394        }
9395        long previousLibVersion = -1;
9396        final int versionCount = versionedLib.size();
9397        for (int i = 0; i < versionCount; i++) {
9398            final long libVersion = versionedLib.keyAt(i);
9399            if (libVersion < pkg.staticSharedLibVersion) {
9400                previousLibVersion = Math.max(previousLibVersion, libVersion);
9401            }
9402        }
9403        if (previousLibVersion >= 0) {
9404            return versionedLib.get(previousLibVersion);
9405        }
9406        return null;
9407    }
9408
9409    public void shutdown() {
9410        mPackageUsage.writeNow(mPackages);
9411        mCompilerStats.writeNow();
9412        mDexManager.writePackageDexUsageNow();
9413    }
9414
9415    @Override
9416    public void dumpProfiles(String packageName) {
9417        PackageParser.Package pkg;
9418        synchronized (mPackages) {
9419            pkg = mPackages.get(packageName);
9420            if (pkg == null) {
9421                throw new IllegalArgumentException("Unknown package: " + packageName);
9422            }
9423        }
9424        /* Only the shell, root, or the app user should be able to dump profiles. */
9425        int callingUid = Binder.getCallingUid();
9426        if (callingUid != Process.SHELL_UID &&
9427            callingUid != Process.ROOT_UID &&
9428            callingUid != pkg.applicationInfo.uid) {
9429            throw new SecurityException("dumpProfiles");
9430        }
9431
9432        synchronized (mInstallLock) {
9433            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9434            mArtManagerService.dumpProfiles(pkg);
9435            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9436        }
9437    }
9438
9439    @Override
9440    public void forceDexOpt(String packageName) {
9441        enforceSystemOrRoot("forceDexOpt");
9442
9443        PackageParser.Package pkg;
9444        synchronized (mPackages) {
9445            pkg = mPackages.get(packageName);
9446            if (pkg == null) {
9447                throw new IllegalArgumentException("Unknown package: " + packageName);
9448            }
9449        }
9450
9451        synchronized (mInstallLock) {
9452            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9453
9454            // Whoever is calling forceDexOpt wants a compiled package.
9455            // Don't use profiles since that may cause compilation to be skipped.
9456            final int res = performDexOptInternalWithDependenciesLI(
9457                    pkg,
9458                    new DexoptOptions(packageName,
9459                            getDefaultCompilerFilter(),
9460                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9461
9462            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9463            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9464                throw new IllegalStateException("Failed to dexopt: " + res);
9465            }
9466        }
9467    }
9468
9469    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9470        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9471            Slog.w(TAG, "Unable to update from " + oldPkg.name
9472                    + " to " + newPkg.packageName
9473                    + ": old package not in system partition");
9474            return false;
9475        } else if (mPackages.get(oldPkg.name) != null) {
9476            Slog.w(TAG, "Unable to update from " + oldPkg.name
9477                    + " to " + newPkg.packageName
9478                    + ": old package still exists");
9479            return false;
9480        }
9481        return true;
9482    }
9483
9484    void removeCodePathLI(File codePath) {
9485        if (codePath.isDirectory()) {
9486            try {
9487                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9488            } catch (InstallerException e) {
9489                Slog.w(TAG, "Failed to remove code path", e);
9490            }
9491        } else {
9492            codePath.delete();
9493        }
9494    }
9495
9496    private int[] resolveUserIds(int userId) {
9497        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9498    }
9499
9500    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9501        if (pkg == null) {
9502            Slog.wtf(TAG, "Package was null!", new Throwable());
9503            return;
9504        }
9505        clearAppDataLeafLIF(pkg, userId, flags);
9506        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9507        for (int i = 0; i < childCount; i++) {
9508            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9509        }
9510
9511        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9512    }
9513
9514    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9515        final PackageSetting ps;
9516        synchronized (mPackages) {
9517            ps = mSettings.mPackages.get(pkg.packageName);
9518        }
9519        for (int realUserId : resolveUserIds(userId)) {
9520            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9521            try {
9522                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9523                        ceDataInode);
9524            } catch (InstallerException e) {
9525                Slog.w(TAG, String.valueOf(e));
9526            }
9527        }
9528    }
9529
9530    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9531        if (pkg == null) {
9532            Slog.wtf(TAG, "Package was null!", new Throwable());
9533            return;
9534        }
9535        destroyAppDataLeafLIF(pkg, userId, flags);
9536        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9537        for (int i = 0; i < childCount; i++) {
9538            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9539        }
9540    }
9541
9542    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9543        final PackageSetting ps;
9544        synchronized (mPackages) {
9545            ps = mSettings.mPackages.get(pkg.packageName);
9546        }
9547        for (int realUserId : resolveUserIds(userId)) {
9548            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9549            try {
9550                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9551                        ceDataInode);
9552            } catch (InstallerException e) {
9553                Slog.w(TAG, String.valueOf(e));
9554            }
9555            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9556        }
9557    }
9558
9559    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9560        if (pkg == null) {
9561            Slog.wtf(TAG, "Package was null!", new Throwable());
9562            return;
9563        }
9564        destroyAppProfilesLeafLIF(pkg);
9565        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9566        for (int i = 0; i < childCount; i++) {
9567            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9568        }
9569    }
9570
9571    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9572        try {
9573            mInstaller.destroyAppProfiles(pkg.packageName);
9574        } catch (InstallerException e) {
9575            Slog.w(TAG, String.valueOf(e));
9576        }
9577    }
9578
9579    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9580        if (pkg == null) {
9581            Slog.wtf(TAG, "Package was null!", new Throwable());
9582            return;
9583        }
9584        mArtManagerService.clearAppProfiles(pkg);
9585        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9586        for (int i = 0; i < childCount; i++) {
9587            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9588        }
9589    }
9590
9591    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9592            long lastUpdateTime) {
9593        // Set parent install/update time
9594        PackageSetting ps = (PackageSetting) pkg.mExtras;
9595        if (ps != null) {
9596            ps.firstInstallTime = firstInstallTime;
9597            ps.lastUpdateTime = lastUpdateTime;
9598        }
9599        // Set children install/update time
9600        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9601        for (int i = 0; i < childCount; i++) {
9602            PackageParser.Package childPkg = pkg.childPackages.get(i);
9603            ps = (PackageSetting) childPkg.mExtras;
9604            if (ps != null) {
9605                ps.firstInstallTime = firstInstallTime;
9606                ps.lastUpdateTime = lastUpdateTime;
9607            }
9608        }
9609    }
9610
9611    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9612            SharedLibraryEntry file,
9613            PackageParser.Package changingLib) {
9614        if (file.path != null) {
9615            usesLibraryFiles.add(file.path);
9616            return;
9617        }
9618        PackageParser.Package p = mPackages.get(file.apk);
9619        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9620            // If we are doing this while in the middle of updating a library apk,
9621            // then we need to make sure to use that new apk for determining the
9622            // dependencies here.  (We haven't yet finished committing the new apk
9623            // to the package manager state.)
9624            if (p == null || p.packageName.equals(changingLib.packageName)) {
9625                p = changingLib;
9626            }
9627        }
9628        if (p != null) {
9629            usesLibraryFiles.addAll(p.getAllCodePaths());
9630            if (p.usesLibraryFiles != null) {
9631                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9632            }
9633        }
9634    }
9635
9636    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9637            PackageParser.Package changingLib) throws PackageManagerException {
9638        if (pkg == null) {
9639            return;
9640        }
9641        // The collection used here must maintain the order of addition (so
9642        // that libraries are searched in the correct order) and must have no
9643        // duplicates.
9644        Set<String> usesLibraryFiles = null;
9645        if (pkg.usesLibraries != null) {
9646            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9647                    null, null, pkg.packageName, changingLib, true,
9648                    pkg.applicationInfo.targetSdkVersion, null);
9649        }
9650        if (pkg.usesStaticLibraries != null) {
9651            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9652                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9653                    pkg.packageName, changingLib, true,
9654                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9655        }
9656        if (pkg.usesOptionalLibraries != null) {
9657            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9658                    null, null, pkg.packageName, changingLib, false,
9659                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9660        }
9661        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9662            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9663        } else {
9664            pkg.usesLibraryFiles = null;
9665        }
9666    }
9667
9668    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9669            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9670            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9671            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9672            throws PackageManagerException {
9673        final int libCount = requestedLibraries.size();
9674        for (int i = 0; i < libCount; i++) {
9675            final String libName = requestedLibraries.get(i);
9676            final long libVersion = requiredVersions != null ? requiredVersions[i]
9677                    : SharedLibraryInfo.VERSION_UNDEFINED;
9678            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9679            if (libEntry == null) {
9680                if (required) {
9681                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9682                            "Package " + packageName + " requires unavailable shared library "
9683                                    + libName + "; failing!");
9684                } else if (DEBUG_SHARED_LIBRARIES) {
9685                    Slog.i(TAG, "Package " + packageName
9686                            + " desires unavailable shared library "
9687                            + libName + "; ignoring!");
9688                }
9689            } else {
9690                if (requiredVersions != null && requiredCertDigests != null) {
9691                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9692                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9693                            "Package " + packageName + " requires unavailable static shared"
9694                                    + " library " + libName + " version "
9695                                    + libEntry.info.getLongVersion() + "; failing!");
9696                    }
9697
9698                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9699                    if (libPkg == null) {
9700                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9701                                "Package " + packageName + " requires unavailable static shared"
9702                                        + " library; failing!");
9703                    }
9704
9705                    final String[] expectedCertDigests = requiredCertDigests[i];
9706
9707
9708                    if (expectedCertDigests.length > 1) {
9709
9710                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9711                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9712                                ? PackageUtils.computeSignaturesSha256Digests(
9713                                libPkg.mSigningDetails.signatures)
9714                                : PackageUtils.computeSignaturesSha256Digests(
9715                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9716
9717                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9718                        // target O we don't parse the "additional-certificate" tags similarly
9719                        // how we only consider all certs only for apps targeting O (see above).
9720                        // Therefore, the size check is safe to make.
9721                        if (expectedCertDigests.length != libCertDigests.length) {
9722                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9723                                    "Package " + packageName + " requires differently signed" +
9724                                            " static shared library; failing!");
9725                        }
9726
9727                        // Use a predictable order as signature order may vary
9728                        Arrays.sort(libCertDigests);
9729                        Arrays.sort(expectedCertDigests);
9730
9731                        final int certCount = libCertDigests.length;
9732                        for (int j = 0; j < certCount; j++) {
9733                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9734                                throw new PackageManagerException(
9735                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9736                                        "Package " + packageName + " requires differently signed" +
9737                                                " static shared library; failing!");
9738                            }
9739                        }
9740                    } else {
9741
9742                        // lib signing cert could have rotated beyond the one expected, check to see
9743                        // if the new one has been blessed by the old
9744                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9745                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9746                            throw new PackageManagerException(
9747                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9748                                    "Package " + packageName + " requires differently signed" +
9749                                            " static shared library; failing!");
9750                        }
9751                    }
9752                }
9753
9754                if (outUsedLibraries == null) {
9755                    // Use LinkedHashSet to preserve the order of files added to
9756                    // usesLibraryFiles while eliminating duplicates.
9757                    outUsedLibraries = new LinkedHashSet<>();
9758                }
9759                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9760            }
9761        }
9762        return outUsedLibraries;
9763    }
9764
9765    private static boolean hasString(List<String> list, List<String> which) {
9766        if (list == null) {
9767            return false;
9768        }
9769        for (int i=list.size()-1; i>=0; i--) {
9770            for (int j=which.size()-1; j>=0; j--) {
9771                if (which.get(j).equals(list.get(i))) {
9772                    return true;
9773                }
9774            }
9775        }
9776        return false;
9777    }
9778
9779    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9780            PackageParser.Package changingPkg) {
9781        ArrayList<PackageParser.Package> res = null;
9782        for (PackageParser.Package pkg : mPackages.values()) {
9783            if (changingPkg != null
9784                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9785                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9786                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9787                            changingPkg.staticSharedLibName)) {
9788                return null;
9789            }
9790            if (res == null) {
9791                res = new ArrayList<>();
9792            }
9793            res.add(pkg);
9794            try {
9795                updateSharedLibrariesLPr(pkg, changingPkg);
9796            } catch (PackageManagerException e) {
9797                // If a system app update or an app and a required lib missing we
9798                // delete the package and for updated system apps keep the data as
9799                // it is better for the user to reinstall than to be in an limbo
9800                // state. Also libs disappearing under an app should never happen
9801                // - just in case.
9802                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9803                    final int flags = pkg.isUpdatedSystemApp()
9804                            ? PackageManager.DELETE_KEEP_DATA : 0;
9805                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9806                            flags , null, true, null);
9807                }
9808                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9809            }
9810        }
9811        return res;
9812    }
9813
9814    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9815            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9816            @Nullable UserHandle user) throws PackageManagerException {
9817        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9818        // If the package has children and this is the first dive in the function
9819        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9820        // whether all packages (parent and children) would be successfully scanned
9821        // before the actual scan since scanning mutates internal state and we want
9822        // to atomically install the package and its children.
9823        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9824            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9825                scanFlags |= SCAN_CHECK_ONLY;
9826            }
9827        } else {
9828            scanFlags &= ~SCAN_CHECK_ONLY;
9829        }
9830
9831        final PackageParser.Package scannedPkg;
9832        try {
9833            // Scan the parent
9834            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9835            // Scan the children
9836            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9837            for (int i = 0; i < childCount; i++) {
9838                PackageParser.Package childPkg = pkg.childPackages.get(i);
9839                scanPackageNewLI(childPkg, parseFlags,
9840                        scanFlags, currentTime, user);
9841            }
9842        } finally {
9843            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9844        }
9845
9846        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9847            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9848        }
9849
9850        return scannedPkg;
9851    }
9852
9853    /** The result of a package scan. */
9854    private static class ScanResult {
9855        /** Whether or not the package scan was successful */
9856        public final boolean success;
9857        /**
9858         * The final package settings. This may be the same object passed in
9859         * the {@link ScanRequest}, but, with modified values.
9860         */
9861        @Nullable public final PackageSetting pkgSetting;
9862        /** ABI code paths that have changed in the package scan */
9863        @Nullable public final List<String> changedAbiCodePath;
9864        public ScanResult(
9865                boolean success,
9866                @Nullable PackageSetting pkgSetting,
9867                @Nullable List<String> changedAbiCodePath) {
9868            this.success = success;
9869            this.pkgSetting = pkgSetting;
9870            this.changedAbiCodePath = changedAbiCodePath;
9871        }
9872    }
9873
9874    /** A package to be scanned */
9875    private static class ScanRequest {
9876        /** The parsed package */
9877        @NonNull public final PackageParser.Package pkg;
9878        /** The package this package replaces */
9879        @Nullable public final PackageParser.Package oldPkg;
9880        /** Shared user settings, if the package has a shared user */
9881        @Nullable public final SharedUserSetting sharedUserSetting;
9882        /**
9883         * Package settings of the currently installed version.
9884         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9885         * during scan.
9886         */
9887        @Nullable public final PackageSetting pkgSetting;
9888        /** A copy of the settings for the currently installed version */
9889        @Nullable public final PackageSetting oldPkgSetting;
9890        /** Package settings for the disabled version on the /system partition */
9891        @Nullable public final PackageSetting disabledPkgSetting;
9892        /** Package settings for the installed version under its original package name */
9893        @Nullable public final PackageSetting originalPkgSetting;
9894        /** The real package name of a renamed application */
9895        @Nullable public final String realPkgName;
9896        public final @ParseFlags int parseFlags;
9897        public final @ScanFlags int scanFlags;
9898        /** The user for which the package is being scanned */
9899        @Nullable public final UserHandle user;
9900        /** Whether or not the platform package is being scanned */
9901        public final boolean isPlatformPackage;
9902        public ScanRequest(
9903                @NonNull PackageParser.Package pkg,
9904                @Nullable SharedUserSetting sharedUserSetting,
9905                @Nullable PackageParser.Package oldPkg,
9906                @Nullable PackageSetting pkgSetting,
9907                @Nullable PackageSetting disabledPkgSetting,
9908                @Nullable PackageSetting originalPkgSetting,
9909                @Nullable String realPkgName,
9910                @ParseFlags int parseFlags,
9911                @ScanFlags int scanFlags,
9912                boolean isPlatformPackage,
9913                @Nullable UserHandle user) {
9914            this.pkg = pkg;
9915            this.oldPkg = oldPkg;
9916            this.pkgSetting = pkgSetting;
9917            this.sharedUserSetting = sharedUserSetting;
9918            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9919            this.disabledPkgSetting = disabledPkgSetting;
9920            this.originalPkgSetting = originalPkgSetting;
9921            this.realPkgName = realPkgName;
9922            this.parseFlags = parseFlags;
9923            this.scanFlags = scanFlags;
9924            this.isPlatformPackage = isPlatformPackage;
9925            this.user = user;
9926        }
9927    }
9928
9929    /**
9930     * Returns the actual scan flags depending upon the state of the other settings.
9931     * <p>Updated system applications will not have the following flags set
9932     * by default and need to be adjusted after the fact:
9933     * <ul>
9934     * <li>{@link #SCAN_AS_SYSTEM}</li>
9935     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9936     * <li>{@link #SCAN_AS_OEM}</li>
9937     * <li>{@link #SCAN_AS_VENDOR}</li>
9938     * <li>{@link #SCAN_AS_PRODUCT}</li>
9939     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9940     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9941     * </ul>
9942     */
9943    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9944            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9945            PackageParser.Package pkg) {
9946        if (disabledPkgSetting != null) {
9947            // updated system application, must at least have SCAN_AS_SYSTEM
9948            scanFlags |= SCAN_AS_SYSTEM;
9949            if ((disabledPkgSetting.pkgPrivateFlags
9950                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9951                scanFlags |= SCAN_AS_PRIVILEGED;
9952            }
9953            if ((disabledPkgSetting.pkgPrivateFlags
9954                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9955                scanFlags |= SCAN_AS_OEM;
9956            }
9957            if ((disabledPkgSetting.pkgPrivateFlags
9958                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9959                scanFlags |= SCAN_AS_VENDOR;
9960            }
9961            if ((disabledPkgSetting.pkgPrivateFlags
9962                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9963                scanFlags |= SCAN_AS_PRODUCT;
9964            }
9965        }
9966        if (pkgSetting != null) {
9967            final int userId = ((user == null) ? 0 : user.getIdentifier());
9968            if (pkgSetting.getInstantApp(userId)) {
9969                scanFlags |= SCAN_AS_INSTANT_APP;
9970            }
9971            if (pkgSetting.getVirtulalPreload(userId)) {
9972                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9973            }
9974        }
9975
9976        // Scan as privileged apps that share a user with a priv-app.
9977        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9978                && (pkg.mSharedUserId != null)) {
9979            SharedUserSetting sharedUserSetting = null;
9980            try {
9981                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9982            } catch (PackageManagerException ignore) {}
9983            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9984                // Exempt SharedUsers signed with the platform key.
9985                // TODO(b/72378145) Fix this exemption. Force signature apps
9986                // to whitelist their privileged permissions just like other
9987                // priv-apps.
9988                synchronized (mPackages) {
9989                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9990                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9991                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9992                        scanFlags |= SCAN_AS_PRIVILEGED;
9993                    }
9994                }
9995            }
9996        }
9997
9998        return scanFlags;
9999    }
10000
10001    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10002    // the results / removing app data needs to be moved up a level to the callers of this
10003    // method. Also, we need to solve the problem of potentially creating a new shared user
10004    // setting. That can probably be done later and patch things up after the fact.
10005    @GuardedBy("mInstallLock")
10006    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10007            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10008            @Nullable UserHandle user) throws PackageManagerException {
10009
10010        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10011        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10012        if (realPkgName != null) {
10013            ensurePackageRenamed(pkg, renamedPkgName);
10014        }
10015        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10016        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10017        final PackageSetting disabledPkgSetting =
10018                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10019
10020        if (mTransferedPackages.contains(pkg.packageName)) {
10021            Slog.w(TAG, "Package " + pkg.packageName
10022                    + " was transferred to another, but its .apk remains");
10023        }
10024
10025        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10026        synchronized (mPackages) {
10027            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10028            assertPackageIsValid(pkg, parseFlags, scanFlags);
10029
10030            SharedUserSetting sharedUserSetting = null;
10031            if (pkg.mSharedUserId != null) {
10032                // SIDE EFFECTS; may potentially allocate a new shared user
10033                sharedUserSetting = mSettings.getSharedUserLPw(
10034                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10035                if (DEBUG_PACKAGE_SCANNING) {
10036                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10037                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10038                                + " (uid=" + sharedUserSetting.userId + "):"
10039                                + " packages=" + sharedUserSetting.packages);
10040                }
10041            }
10042
10043            boolean scanSucceeded = false;
10044            try {
10045                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10046                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10047                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10048                        (pkg == mPlatformPackage), user);
10049                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10050                if (result.success) {
10051                    commitScanResultsLocked(request, result);
10052                }
10053                scanSucceeded = true;
10054            } finally {
10055                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10056                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10057                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10058                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10059                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10060                  }
10061            }
10062        }
10063        return pkg;
10064    }
10065
10066    /**
10067     * Commits the package scan and modifies system state.
10068     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10069     * of committing the package, leaving the system in an inconsistent state.
10070     * This needs to be fixed so, once we get to this point, no errors are
10071     * possible and the system is not left in an inconsistent state.
10072     */
10073    @GuardedBy("mPackages")
10074    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10075            throws PackageManagerException {
10076        final PackageParser.Package pkg = request.pkg;
10077        final PackageParser.Package oldPkg = request.oldPkg;
10078        final @ParseFlags int parseFlags = request.parseFlags;
10079        final @ScanFlags int scanFlags = request.scanFlags;
10080        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10081        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10082        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10083        final UserHandle user = request.user;
10084        final String realPkgName = request.realPkgName;
10085        final PackageSetting pkgSetting = result.pkgSetting;
10086        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10087        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10088
10089        if (newPkgSettingCreated) {
10090            if (originalPkgSetting != null) {
10091                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10092            }
10093            // THROWS: when we can't allocate a user id. add call to check if there's
10094            // enough space to ensure we won't throw; otherwise, don't modify state
10095            mSettings.addUserToSettingLPw(pkgSetting);
10096
10097            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10098                mTransferedPackages.add(originalPkgSetting.name);
10099            }
10100        }
10101        // TODO(toddke): Consider a method specifically for modifying the Package object
10102        // post scan; or, moving this stuff out of the Package object since it has nothing
10103        // to do with the package on disk.
10104        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10105        // for creating the application ID. If we did this earlier, we would be saving the
10106        // correct ID.
10107        pkg.applicationInfo.uid = pkgSetting.appId;
10108
10109        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10110
10111        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10112            mTransferedPackages.add(pkg.packageName);
10113        }
10114
10115        // THROWS: when requested libraries that can't be found. it only changes
10116        // the state of the passed in pkg object, so, move to the top of the method
10117        // and allow it to abort
10118        if ((scanFlags & SCAN_BOOTING) == 0
10119                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10120            // Check all shared libraries and map to their actual file path.
10121            // We only do this here for apps not on a system dir, because those
10122            // are the only ones that can fail an install due to this.  We
10123            // will take care of the system apps by updating all of their
10124            // library paths after the scan is done. Also during the initial
10125            // scan don't update any libs as we do this wholesale after all
10126            // apps are scanned to avoid dependency based scanning.
10127            updateSharedLibrariesLPr(pkg, null);
10128        }
10129
10130        // All versions of a static shared library are referenced with the same
10131        // package name. Internally, we use a synthetic package name to allow
10132        // multiple versions of the same shared library to be installed. So,
10133        // we need to generate the synthetic package name of the latest shared
10134        // library in order to compare signatures.
10135        PackageSetting signatureCheckPs = pkgSetting;
10136        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10137            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10138            if (libraryEntry != null) {
10139                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10140            }
10141        }
10142
10143        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10144        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10145            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10146                // We just determined the app is signed correctly, so bring
10147                // over the latest parsed certs.
10148                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10149            } else {
10150                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10151                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10152                            "Package " + pkg.packageName + " upgrade keys do not match the "
10153                                    + "previously installed version");
10154                } else {
10155                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10156                    String msg = "System package " + pkg.packageName
10157                            + " signature changed; retaining data.";
10158                    reportSettingsProblem(Log.WARN, msg);
10159                }
10160            }
10161        } else {
10162            try {
10163                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10164                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10165                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10166                        pkg.mSigningDetails, compareCompat, compareRecover);
10167                // The new KeySets will be re-added later in the scanning process.
10168                if (compatMatch) {
10169                    synchronized (mPackages) {
10170                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10171                    }
10172                }
10173                // We just determined the app is signed correctly, so bring
10174                // over the latest parsed certs.
10175                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10176
10177
10178                // if this is is a sharedUser, check to see if the new package is signed by a newer
10179                // signing certificate than the existing one, and if so, copy over the new details
10180                if (signatureCheckPs.sharedUser != null
10181                        && pkg.mSigningDetails.hasAncestor(
10182                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10183                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10184                }
10185            } catch (PackageManagerException e) {
10186                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10187                    throw e;
10188                }
10189                // The signature has changed, but this package is in the system
10190                // image...  let's recover!
10191                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10192                // If the system app is part of a shared user we allow that shared user to change
10193                // signatures as well in part as part of an OTA.
10194                if (signatureCheckPs.sharedUser != null) {
10195                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10196                }
10197                // File a report about this.
10198                String msg = "System package " + pkg.packageName
10199                        + " signature changed; retaining data.";
10200                reportSettingsProblem(Log.WARN, msg);
10201            } catch (IllegalArgumentException e) {
10202
10203                // should never happen: certs matched when checking, but not when comparing
10204                // old to new for sharedUser
10205                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10206                        "Signing certificates comparison made on incomparable signing details"
10207                        + " but somehow passed verifySignatures!");
10208            }
10209        }
10210
10211        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10212            // This package wants to adopt ownership of permissions from
10213            // another package.
10214            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10215                final String origName = pkg.mAdoptPermissions.get(i);
10216                final PackageSetting orig = mSettings.getPackageLPr(origName);
10217                if (orig != null) {
10218                    if (verifyPackageUpdateLPr(orig, pkg)) {
10219                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10220                                + pkg.packageName);
10221                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10222                    }
10223                }
10224            }
10225        }
10226
10227        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10228            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10229                final String codePathString = changedAbiCodePath.get(i);
10230                try {
10231                    mInstaller.rmdex(codePathString,
10232                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10233                } catch (InstallerException ignored) {
10234                }
10235            }
10236        }
10237
10238        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10239            if (oldPkgSetting != null) {
10240                synchronized (mPackages) {
10241                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10242                }
10243            }
10244        } else {
10245            final int userId = user == null ? 0 : user.getIdentifier();
10246            // Modify state for the given package setting
10247            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10248                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10249            if (pkgSetting.getInstantApp(userId)) {
10250                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10251            }
10252        }
10253    }
10254
10255    /**
10256     * Returns the "real" name of the package.
10257     * <p>This may differ from the package's actual name if the application has already
10258     * been installed under one of this package's original names.
10259     */
10260    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10261            @Nullable String renamedPkgName) {
10262        if (isPackageRenamed(pkg, renamedPkgName)) {
10263            return pkg.mRealPackage;
10264        }
10265        return null;
10266    }
10267
10268    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10269    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10270            @Nullable String renamedPkgName) {
10271        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10272    }
10273
10274    /**
10275     * Returns the original package setting.
10276     * <p>A package can migrate its name during an update. In this scenario, a package
10277     * designates a set of names that it considers as one of its original names.
10278     * <p>An original package must be signed identically and it must have the same
10279     * shared user [if any].
10280     */
10281    @GuardedBy("mPackages")
10282    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10283            @Nullable String renamedPkgName) {
10284        if (!isPackageRenamed(pkg, renamedPkgName)) {
10285            return null;
10286        }
10287        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10288            final PackageSetting originalPs =
10289                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10290            if (originalPs != null) {
10291                // the package is already installed under its original name...
10292                // but, should we use it?
10293                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10294                    // the new package is incompatible with the original
10295                    continue;
10296                } else if (originalPs.sharedUser != null) {
10297                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10298                        // the shared user id is incompatible with the original
10299                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10300                                + " to " + pkg.packageName + ": old uid "
10301                                + originalPs.sharedUser.name
10302                                + " differs from " + pkg.mSharedUserId);
10303                        continue;
10304                    }
10305                    // TODO: Add case when shared user id is added [b/28144775]
10306                } else {
10307                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10308                            + pkg.packageName + " to old name " + originalPs.name);
10309                }
10310                return originalPs;
10311            }
10312        }
10313        return null;
10314    }
10315
10316    /**
10317     * Renames the package if it was installed under a different name.
10318     * <p>When we've already installed the package under an original name, update
10319     * the new package so we can continue to have the old name.
10320     */
10321    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10322            @NonNull String renamedPackageName) {
10323        if (pkg.mOriginalPackages == null
10324                || !pkg.mOriginalPackages.contains(renamedPackageName)
10325                || pkg.packageName.equals(renamedPackageName)) {
10326            return;
10327        }
10328        pkg.setPackageName(renamedPackageName);
10329    }
10330
10331    /**
10332     * Just scans the package without any side effects.
10333     * <p>Not entirely true at the moment. There is still one side effect -- this
10334     * method potentially modifies a live {@link PackageSetting} object representing
10335     * the package being scanned. This will be resolved in the future.
10336     *
10337     * @param request Information about the package to be scanned
10338     * @param isUnderFactoryTest Whether or not the device is under factory test
10339     * @param currentTime The current time, in millis
10340     * @return The results of the scan
10341     */
10342    @GuardedBy("mInstallLock")
10343    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10344            boolean isUnderFactoryTest, long currentTime)
10345                    throws PackageManagerException {
10346        final PackageParser.Package pkg = request.pkg;
10347        PackageSetting pkgSetting = request.pkgSetting;
10348        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10349        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10350        final @ParseFlags int parseFlags = request.parseFlags;
10351        final @ScanFlags int scanFlags = request.scanFlags;
10352        final String realPkgName = request.realPkgName;
10353        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10354        final UserHandle user = request.user;
10355        final boolean isPlatformPackage = request.isPlatformPackage;
10356
10357        List<String> changedAbiCodePath = null;
10358
10359        if (DEBUG_PACKAGE_SCANNING) {
10360            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10361                Log.d(TAG, "Scanning package " + pkg.packageName);
10362        }
10363
10364        if (Build.IS_DEBUGGABLE &&
10365                pkg.isPrivileged() &&
10366                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10367            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10368        }
10369
10370        // Initialize package source and resource directories
10371        final File scanFile = new File(pkg.codePath);
10372        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10373        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10374
10375        // We keep references to the derived CPU Abis from settings in oder to reuse
10376        // them in the case where we're not upgrading or booting for the first time.
10377        String primaryCpuAbiFromSettings = null;
10378        String secondaryCpuAbiFromSettings = null;
10379        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10380
10381        if (!needToDeriveAbi) {
10382            if (pkgSetting != null) {
10383                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10384                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10385            } else {
10386                // Re-scanning a system package after uninstalling updates; need to derive ABI
10387                needToDeriveAbi = true;
10388            }
10389        }
10390
10391        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10392            PackageManagerService.reportSettingsProblem(Log.WARN,
10393                    "Package " + pkg.packageName + " shared user changed from "
10394                            + (pkgSetting.sharedUser != null
10395                            ? pkgSetting.sharedUser.name : "<nothing>")
10396                            + " to "
10397                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10398                            + "; replacing with new");
10399            pkgSetting = null;
10400        }
10401
10402        String[] usesStaticLibraries = null;
10403        if (pkg.usesStaticLibraries != null) {
10404            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10405            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10406        }
10407        final boolean createNewPackage = (pkgSetting == null);
10408        if (createNewPackage) {
10409            final String parentPackageName = (pkg.parentPackage != null)
10410                    ? pkg.parentPackage.packageName : null;
10411            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10412            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10413            // REMOVE SharedUserSetting from method; update in a separate call
10414            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10415                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10416                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10417                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10418                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10419                    user, true /*allowInstall*/, instantApp, virtualPreload,
10420                    parentPackageName, pkg.getChildPackageNames(),
10421                    UserManagerService.getInstance(), usesStaticLibraries,
10422                    pkg.usesStaticLibrariesVersions);
10423        } else {
10424            // REMOVE SharedUserSetting from method; update in a separate call.
10425            //
10426            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10427            // secondaryCpuAbi are not known at this point so we always update them
10428            // to null here, only to reset them at a later point.
10429            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10430                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10431                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10432                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10433                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10434                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10435        }
10436        if (createNewPackage && originalPkgSetting != null) {
10437            // This is the initial transition from the original package, so,
10438            // fix up the new package's name now. We must do this after looking
10439            // up the package under its new name, so getPackageLP takes care of
10440            // fiddling things correctly.
10441            pkg.setPackageName(originalPkgSetting.name);
10442
10443            // File a report about this.
10444            String msg = "New package " + pkgSetting.realName
10445                    + " renamed to replace old package " + pkgSetting.name;
10446            reportSettingsProblem(Log.WARN, msg);
10447        }
10448
10449        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10450        // for existing packages, change the install state; but, only if it's explicitly specified
10451        if (!createNewPackage) {
10452            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10453            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10454            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10455        }
10456
10457        if (disabledPkgSetting != null) {
10458            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10459        }
10460
10461        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10462        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10463        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10464        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10465        // least restrictive selinux domain.
10466        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10467        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10468        // ensures that all packages continue to run in the same selinux domain.
10469        final int targetSdkVersion =
10470            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10471            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10472        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10473        // They currently can be if the sharedUser apps are signed with the platform key.
10474        final boolean isPrivileged = (sharedUserSetting != null) ?
10475            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10476
10477        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10478                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10479        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10480                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10481
10482        pkg.mExtras = pkgSetting;
10483        pkg.applicationInfo.processName = fixProcessName(
10484                pkg.applicationInfo.packageName,
10485                pkg.applicationInfo.processName);
10486
10487        if (!isPlatformPackage) {
10488            // Get all of our default paths setup
10489            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10490        }
10491
10492        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10493
10494        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10495            if (needToDeriveAbi) {
10496                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10497                final boolean extractNativeLibs = !pkg.isLibrary();
10498                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10499                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10500
10501                // Some system apps still use directory structure for native libraries
10502                // in which case we might end up not detecting abi solely based on apk
10503                // structure. Try to detect abi based on directory structure.
10504                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10505                        pkg.applicationInfo.primaryCpuAbi == null) {
10506                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10507                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10508                }
10509            } else {
10510                // This is not a first boot or an upgrade, don't bother deriving the
10511                // ABI during the scan. Instead, trust the value that was stored in the
10512                // package setting.
10513                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10514                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10515
10516                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10517
10518                if (DEBUG_ABI_SELECTION) {
10519                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10520                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10521                            pkg.applicationInfo.secondaryCpuAbi);
10522                }
10523            }
10524        } else {
10525            if ((scanFlags & SCAN_MOVE) != 0) {
10526                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10527                // but we already have this packages package info in the PackageSetting. We just
10528                // use that and derive the native library path based on the new codepath.
10529                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10530                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10531            }
10532
10533            // Set native library paths again. For moves, the path will be updated based on the
10534            // ABIs we've determined above. For non-moves, the path will be updated based on the
10535            // ABIs we determined during compilation, but the path will depend on the final
10536            // package path (after the rename away from the stage path).
10537            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10538        }
10539
10540        // This is a special case for the "system" package, where the ABI is
10541        // dictated by the zygote configuration (and init.rc). We should keep track
10542        // of this ABI so that we can deal with "normal" applications that run under
10543        // the same UID correctly.
10544        if (isPlatformPackage) {
10545            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10546                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10547        }
10548
10549        // If there's a mismatch between the abi-override in the package setting
10550        // and the abiOverride specified for the install. Warn about this because we
10551        // would've already compiled the app without taking the package setting into
10552        // account.
10553        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10554            if (cpuAbiOverride == null && pkg.packageName != null) {
10555                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10556                        " for package " + pkg.packageName);
10557            }
10558        }
10559
10560        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10561        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10562        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10563
10564        // Copy the derived override back to the parsed package, so that we can
10565        // update the package settings accordingly.
10566        pkg.cpuAbiOverride = cpuAbiOverride;
10567
10568        if (DEBUG_ABI_SELECTION) {
10569            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10570                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10571                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10572        }
10573
10574        // Push the derived path down into PackageSettings so we know what to
10575        // clean up at uninstall time.
10576        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10577
10578        if (DEBUG_ABI_SELECTION) {
10579            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10580                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10581                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10582        }
10583
10584        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10585            // We don't do this here during boot because we can do it all
10586            // at once after scanning all existing packages.
10587            //
10588            // We also do this *before* we perform dexopt on this package, so that
10589            // we can avoid redundant dexopts, and also to make sure we've got the
10590            // code and package path correct.
10591            changedAbiCodePath =
10592                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10593        }
10594
10595        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10596                android.Manifest.permission.FACTORY_TEST)) {
10597            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10598        }
10599
10600        if (isSystemApp(pkg)) {
10601            pkgSetting.isOrphaned = true;
10602        }
10603
10604        // Take care of first install / last update times.
10605        final long scanFileTime = getLastModifiedTime(pkg);
10606        if (currentTime != 0) {
10607            if (pkgSetting.firstInstallTime == 0) {
10608                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10609            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10610                pkgSetting.lastUpdateTime = currentTime;
10611            }
10612        } else if (pkgSetting.firstInstallTime == 0) {
10613            // We need *something*.  Take time time stamp of the file.
10614            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10615        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10616            if (scanFileTime != pkgSetting.timeStamp) {
10617                // A package on the system image has changed; consider this
10618                // to be an update.
10619                pkgSetting.lastUpdateTime = scanFileTime;
10620            }
10621        }
10622        pkgSetting.setTimeStamp(scanFileTime);
10623
10624        pkgSetting.pkg = pkg;
10625        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10626        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10627            pkgSetting.versionCode = pkg.getLongVersionCode();
10628        }
10629        // Update volume if needed
10630        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10631        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10632            Slog.i(PackageManagerService.TAG,
10633                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10634                    + " package " + pkg.packageName
10635                    + " volume from " + pkgSetting.volumeUuid
10636                    + " to " + volumeUuid);
10637            pkgSetting.volumeUuid = volumeUuid;
10638        }
10639
10640        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10641    }
10642
10643    /**
10644     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10645     */
10646    private static boolean apkHasCode(String fileName) {
10647        StrictJarFile jarFile = null;
10648        try {
10649            jarFile = new StrictJarFile(fileName,
10650                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10651            return jarFile.findEntry("classes.dex") != null;
10652        } catch (IOException ignore) {
10653        } finally {
10654            try {
10655                if (jarFile != null) {
10656                    jarFile.close();
10657                }
10658            } catch (IOException ignore) {}
10659        }
10660        return false;
10661    }
10662
10663    /**
10664     * Enforces code policy for the package. This ensures that if an APK has
10665     * declared hasCode="true" in its manifest that the APK actually contains
10666     * code.
10667     *
10668     * @throws PackageManagerException If bytecode could not be found when it should exist
10669     */
10670    private static void assertCodePolicy(PackageParser.Package pkg)
10671            throws PackageManagerException {
10672        final boolean shouldHaveCode =
10673                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10674        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10675            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10676                    "Package " + pkg.baseCodePath + " code is missing");
10677        }
10678
10679        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10680            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10681                final boolean splitShouldHaveCode =
10682                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10683                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10684                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10685                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10686                }
10687            }
10688        }
10689    }
10690
10691    /**
10692     * Applies policy to the parsed package based upon the given policy flags.
10693     * Ensures the package is in a good state.
10694     * <p>
10695     * Implementation detail: This method must NOT have any side effect. It would
10696     * ideally be static, but, it requires locks to read system state.
10697     */
10698    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10699            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10700        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10701            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10702            if (pkg.applicationInfo.isDirectBootAware()) {
10703                // we're direct boot aware; set for all components
10704                for (PackageParser.Service s : pkg.services) {
10705                    s.info.encryptionAware = s.info.directBootAware = true;
10706                }
10707                for (PackageParser.Provider p : pkg.providers) {
10708                    p.info.encryptionAware = p.info.directBootAware = true;
10709                }
10710                for (PackageParser.Activity a : pkg.activities) {
10711                    a.info.encryptionAware = a.info.directBootAware = true;
10712                }
10713                for (PackageParser.Activity r : pkg.receivers) {
10714                    r.info.encryptionAware = r.info.directBootAware = true;
10715                }
10716            }
10717            if (compressedFileExists(pkg.codePath)) {
10718                pkg.isStub = true;
10719            }
10720        } else {
10721            // non system apps can't be flagged as core
10722            pkg.coreApp = false;
10723            // clear flags not applicable to regular apps
10724            pkg.applicationInfo.flags &=
10725                    ~ApplicationInfo.FLAG_PERSISTENT;
10726            pkg.applicationInfo.privateFlags &=
10727                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10728            pkg.applicationInfo.privateFlags &=
10729                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10730            // cap permission priorities
10731            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10732                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10733                    pkg.permissionGroups.get(i).info.priority = 0;
10734                }
10735            }
10736        }
10737        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10738            // clear protected broadcasts
10739            pkg.protectedBroadcasts = null;
10740            // ignore export request for single user receivers
10741            if (pkg.receivers != null) {
10742                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10743                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10744                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10745                        receiver.info.exported = false;
10746                    }
10747                }
10748            }
10749            // ignore export request for single user services
10750            if (pkg.services != null) {
10751                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10752                    final PackageParser.Service service = pkg.services.get(i);
10753                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10754                        service.info.exported = false;
10755                    }
10756                }
10757            }
10758            // ignore export request for single user providers
10759            if (pkg.providers != null) {
10760                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10761                    final PackageParser.Provider provider = pkg.providers.get(i);
10762                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10763                        provider.info.exported = false;
10764                    }
10765                }
10766            }
10767        }
10768
10769        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10770            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10771        }
10772
10773        if ((scanFlags & SCAN_AS_OEM) != 0) {
10774            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10775        }
10776
10777        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10778            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10779        }
10780
10781        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10782            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10783        }
10784
10785        // Check if the package is signed with the same key as the platform package.
10786        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10787                (platformPkg != null && compareSignatures(
10788                        platformPkg.mSigningDetails.signatures,
10789                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10790            pkg.applicationInfo.privateFlags |=
10791                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10792        }
10793
10794        if (!isSystemApp(pkg)) {
10795            // Only system apps can use these features.
10796            pkg.mOriginalPackages = null;
10797            pkg.mRealPackage = null;
10798            pkg.mAdoptPermissions = null;
10799        }
10800    }
10801
10802    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10803            throws PackageManagerException {
10804        if (object == null) {
10805            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10806        }
10807        return object;
10808    }
10809
10810    /**
10811     * Asserts the parsed package is valid according to the given policy. If the
10812     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10813     * <p>
10814     * Implementation detail: This method must NOT have any side effects. It would
10815     * ideally be static, but, it requires locks to read system state.
10816     *
10817     * @throws PackageManagerException If the package fails any of the validation checks
10818     */
10819    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10820            final @ScanFlags int scanFlags)
10821                    throws PackageManagerException {
10822        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10823            assertCodePolicy(pkg);
10824        }
10825
10826        if (pkg.applicationInfo.getCodePath() == null ||
10827                pkg.applicationInfo.getResourcePath() == null) {
10828            // Bail out. The resource and code paths haven't been set.
10829            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10830                    "Code and resource paths haven't been set correctly");
10831        }
10832
10833        // Make sure we're not adding any bogus keyset info
10834        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10835        ksms.assertScannedPackageValid(pkg);
10836
10837        synchronized (mPackages) {
10838            // The special "android" package can only be defined once
10839            if (pkg.packageName.equals("android")) {
10840                if (mAndroidApplication != null) {
10841                    Slog.w(TAG, "*************************************************");
10842                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10843                    Slog.w(TAG, " codePath=" + pkg.codePath);
10844                    Slog.w(TAG, "*************************************************");
10845                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10846                            "Core android package being redefined.  Skipping.");
10847                }
10848            }
10849
10850            // A package name must be unique; don't allow duplicates
10851            if (mPackages.containsKey(pkg.packageName)) {
10852                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10853                        "Application package " + pkg.packageName
10854                        + " already installed.  Skipping duplicate.");
10855            }
10856
10857            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10858                // Static libs have a synthetic package name containing the version
10859                // but we still want the base name to be unique.
10860                if (mPackages.containsKey(pkg.manifestPackageName)) {
10861                    throw new PackageManagerException(
10862                            "Duplicate static shared lib provider package");
10863                }
10864
10865                // Static shared libraries should have at least O target SDK
10866                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10867                    throw new PackageManagerException(
10868                            "Packages declaring static-shared libs must target O SDK or higher");
10869                }
10870
10871                // Package declaring static a shared lib cannot be instant apps
10872                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10873                    throw new PackageManagerException(
10874                            "Packages declaring static-shared libs cannot be instant apps");
10875                }
10876
10877                // Package declaring static a shared lib cannot be renamed since the package
10878                // name is synthetic and apps can't code around package manager internals.
10879                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10880                    throw new PackageManagerException(
10881                            "Packages declaring static-shared libs cannot be renamed");
10882                }
10883
10884                // Package declaring static a shared lib cannot declare child packages
10885                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10886                    throw new PackageManagerException(
10887                            "Packages declaring static-shared libs cannot have child packages");
10888                }
10889
10890                // Package declaring static a shared lib cannot declare dynamic libs
10891                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10892                    throw new PackageManagerException(
10893                            "Packages declaring static-shared libs cannot declare dynamic libs");
10894                }
10895
10896                // Package declaring static a shared lib cannot declare shared users
10897                if (pkg.mSharedUserId != null) {
10898                    throw new PackageManagerException(
10899                            "Packages declaring static-shared libs cannot declare shared users");
10900                }
10901
10902                // Static shared libs cannot declare activities
10903                if (!pkg.activities.isEmpty()) {
10904                    throw new PackageManagerException(
10905                            "Static shared libs cannot declare activities");
10906                }
10907
10908                // Static shared libs cannot declare services
10909                if (!pkg.services.isEmpty()) {
10910                    throw new PackageManagerException(
10911                            "Static shared libs cannot declare services");
10912                }
10913
10914                // Static shared libs cannot declare providers
10915                if (!pkg.providers.isEmpty()) {
10916                    throw new PackageManagerException(
10917                            "Static shared libs cannot declare content providers");
10918                }
10919
10920                // Static shared libs cannot declare receivers
10921                if (!pkg.receivers.isEmpty()) {
10922                    throw new PackageManagerException(
10923                            "Static shared libs cannot declare broadcast receivers");
10924                }
10925
10926                // Static shared libs cannot declare permission groups
10927                if (!pkg.permissionGroups.isEmpty()) {
10928                    throw new PackageManagerException(
10929                            "Static shared libs cannot declare permission groups");
10930                }
10931
10932                // Static shared libs cannot declare permissions
10933                if (!pkg.permissions.isEmpty()) {
10934                    throw new PackageManagerException(
10935                            "Static shared libs cannot declare permissions");
10936                }
10937
10938                // Static shared libs cannot declare protected broadcasts
10939                if (pkg.protectedBroadcasts != null) {
10940                    throw new PackageManagerException(
10941                            "Static shared libs cannot declare protected broadcasts");
10942                }
10943
10944                // Static shared libs cannot be overlay targets
10945                if (pkg.mOverlayTarget != null) {
10946                    throw new PackageManagerException(
10947                            "Static shared libs cannot be overlay targets");
10948                }
10949
10950                // The version codes must be ordered as lib versions
10951                long minVersionCode = Long.MIN_VALUE;
10952                long maxVersionCode = Long.MAX_VALUE;
10953
10954                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10955                        pkg.staticSharedLibName);
10956                if (versionedLib != null) {
10957                    final int versionCount = versionedLib.size();
10958                    for (int i = 0; i < versionCount; i++) {
10959                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10960                        final long libVersionCode = libInfo.getDeclaringPackage()
10961                                .getLongVersionCode();
10962                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10963                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10964                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10965                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10966                        } else {
10967                            minVersionCode = maxVersionCode = libVersionCode;
10968                            break;
10969                        }
10970                    }
10971                }
10972                if (pkg.getLongVersionCode() < minVersionCode
10973                        || pkg.getLongVersionCode() > maxVersionCode) {
10974                    throw new PackageManagerException("Static shared"
10975                            + " lib version codes must be ordered as lib versions");
10976                }
10977            }
10978
10979            // Only privileged apps and updated privileged apps can add child packages.
10980            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10981                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10982                    throw new PackageManagerException("Only privileged apps can add child "
10983                            + "packages. Ignoring package " + pkg.packageName);
10984                }
10985                final int childCount = pkg.childPackages.size();
10986                for (int i = 0; i < childCount; i++) {
10987                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10988                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10989                            childPkg.packageName)) {
10990                        throw new PackageManagerException("Can't override child of "
10991                                + "another disabled app. Ignoring package " + pkg.packageName);
10992                    }
10993                }
10994            }
10995
10996            // If we're only installing presumed-existing packages, require that the
10997            // scanned APK is both already known and at the path previously established
10998            // for it.  Previously unknown packages we pick up normally, but if we have an
10999            // a priori expectation about this package's install presence, enforce it.
11000            // With a singular exception for new system packages. When an OTA contains
11001            // a new system package, we allow the codepath to change from a system location
11002            // to the user-installed location. If we don't allow this change, any newer,
11003            // user-installed version of the application will be ignored.
11004            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11005                if (mExpectingBetter.containsKey(pkg.packageName)) {
11006                    logCriticalInfo(Log.WARN,
11007                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11008                } else {
11009                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11010                    if (known != null) {
11011                        if (DEBUG_PACKAGE_SCANNING) {
11012                            Log.d(TAG, "Examining " + pkg.codePath
11013                                    + " and requiring known paths " + known.codePathString
11014                                    + " & " + known.resourcePathString);
11015                        }
11016                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11017                                || !pkg.applicationInfo.getResourcePath().equals(
11018                                        known.resourcePathString)) {
11019                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11020                                    "Application package " + pkg.packageName
11021                                    + " found at " + pkg.applicationInfo.getCodePath()
11022                                    + " but expected at " + known.codePathString
11023                                    + "; ignoring.");
11024                        }
11025                    } else {
11026                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11027                                "Application package " + pkg.packageName
11028                                + " not found; ignoring.");
11029                    }
11030                }
11031            }
11032
11033            // Verify that this new package doesn't have any content providers
11034            // that conflict with existing packages.  Only do this if the
11035            // package isn't already installed, since we don't want to break
11036            // things that are installed.
11037            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11038                final int N = pkg.providers.size();
11039                int i;
11040                for (i=0; i<N; i++) {
11041                    PackageParser.Provider p = pkg.providers.get(i);
11042                    if (p.info.authority != null) {
11043                        String names[] = p.info.authority.split(";");
11044                        for (int j = 0; j < names.length; j++) {
11045                            if (mProvidersByAuthority.containsKey(names[j])) {
11046                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11047                                final String otherPackageName =
11048                                        ((other != null && other.getComponentName() != null) ?
11049                                                other.getComponentName().getPackageName() : "?");
11050                                throw new PackageManagerException(
11051                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11052                                        "Can't install because provider name " + names[j]
11053                                                + " (in package " + pkg.applicationInfo.packageName
11054                                                + ") is already used by " + otherPackageName);
11055                            }
11056                        }
11057                    }
11058                }
11059            }
11060
11061            // Verify that packages sharing a user with a privileged app are marked as privileged.
11062            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11063                SharedUserSetting sharedUserSetting = null;
11064                try {
11065                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11066                } catch (PackageManagerException ignore) {}
11067                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11068                    // Exempt SharedUsers signed with the platform key.
11069                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11070                    if ((platformPkgSetting.signatures.mSigningDetails
11071                            != PackageParser.SigningDetails.UNKNOWN)
11072                            && (compareSignatures(
11073                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11074                                    pkg.mSigningDetails.signatures)
11075                                            != PackageManager.SIGNATURE_MATCH)) {
11076                        throw new PackageManagerException("Apps that share a user with a " +
11077                                "privileged app must themselves be marked as privileged. " +
11078                                pkg.packageName + " shares privileged user " +
11079                                pkg.mSharedUserId + ".");
11080                    }
11081                }
11082            }
11083
11084            // Apply policies specific for runtime resource overlays (RROs).
11085            if (pkg.mOverlayTarget != null) {
11086                // System overlays have some restrictions on their use of the 'static' state.
11087                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11088                    // We are scanning a system overlay. This can be the first scan of the
11089                    // system/vendor/oem partition, or an update to the system overlay.
11090                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11091                        // This must be an update to a system overlay.
11092                        final PackageSetting previousPkg = assertNotNull(
11093                                mSettings.getPackageLPr(pkg.packageName),
11094                                "previous package state not present");
11095
11096                        // Static overlays cannot be updated.
11097                        if (previousPkg.pkg.mOverlayIsStatic) {
11098                            throw new PackageManagerException("Overlay " + pkg.packageName +
11099                                    " is static and cannot be upgraded.");
11100                        // Non-static overlays cannot be converted to static overlays.
11101                        } else if (pkg.mOverlayIsStatic) {
11102                            throw new PackageManagerException("Overlay " + pkg.packageName +
11103                                    " cannot be upgraded into a static overlay.");
11104                        }
11105                    }
11106                } else {
11107                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11108                    if (pkg.mOverlayIsStatic) {
11109                        throw new PackageManagerException("Overlay " + pkg.packageName +
11110                                " is static but not pre-installed.");
11111                    }
11112
11113                    // The only case where we allow installation of a non-system overlay is when
11114                    // its signature is signed with the platform certificate.
11115                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11116                    if ((platformPkgSetting.signatures.mSigningDetails
11117                            != PackageParser.SigningDetails.UNKNOWN)
11118                            && (compareSignatures(
11119                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11120                                    pkg.mSigningDetails.signatures)
11121                                            != PackageManager.SIGNATURE_MATCH)) {
11122                        throw new PackageManagerException("Overlay " + pkg.packageName +
11123                                " must be signed with the platform certificate.");
11124                    }
11125                }
11126            }
11127        }
11128    }
11129
11130    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11131            int type, String declaringPackageName, long declaringVersionCode) {
11132        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11133        if (versionedLib == null) {
11134            versionedLib = new LongSparseArray<>();
11135            mSharedLibraries.put(name, versionedLib);
11136            if (type == SharedLibraryInfo.TYPE_STATIC) {
11137                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11138            }
11139        } else if (versionedLib.indexOfKey(version) >= 0) {
11140            return false;
11141        }
11142        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11143                version, type, declaringPackageName, declaringVersionCode);
11144        versionedLib.put(version, libEntry);
11145        return true;
11146    }
11147
11148    private boolean removeSharedLibraryLPw(String name, long version) {
11149        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11150        if (versionedLib == null) {
11151            return false;
11152        }
11153        final int libIdx = versionedLib.indexOfKey(version);
11154        if (libIdx < 0) {
11155            return false;
11156        }
11157        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11158        versionedLib.remove(version);
11159        if (versionedLib.size() <= 0) {
11160            mSharedLibraries.remove(name);
11161            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11162                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11163                        .getPackageName());
11164            }
11165        }
11166        return true;
11167    }
11168
11169    /**
11170     * Adds a scanned package to the system. When this method is finished, the package will
11171     * be available for query, resolution, etc...
11172     */
11173    private void commitPackageSettings(PackageParser.Package pkg,
11174            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11175            final @ScanFlags int scanFlags, boolean chatty) {
11176        final String pkgName = pkg.packageName;
11177        if (mCustomResolverComponentName != null &&
11178                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11179            setUpCustomResolverActivity(pkg);
11180        }
11181
11182        if (pkg.packageName.equals("android")) {
11183            synchronized (mPackages) {
11184                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11185                    // Set up information for our fall-back user intent resolution activity.
11186                    mPlatformPackage = pkg;
11187                    pkg.mVersionCode = mSdkVersion;
11188                    pkg.mVersionCodeMajor = 0;
11189                    mAndroidApplication = pkg.applicationInfo;
11190                    if (!mResolverReplaced) {
11191                        mResolveActivity.applicationInfo = mAndroidApplication;
11192                        mResolveActivity.name = ResolverActivity.class.getName();
11193                        mResolveActivity.packageName = mAndroidApplication.packageName;
11194                        mResolveActivity.processName = "system:ui";
11195                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11196                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11197                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11198                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11199                        mResolveActivity.exported = true;
11200                        mResolveActivity.enabled = true;
11201                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11202                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11203                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11204                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11205                                | ActivityInfo.CONFIG_ORIENTATION
11206                                | ActivityInfo.CONFIG_KEYBOARD
11207                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11208                        mResolveInfo.activityInfo = mResolveActivity;
11209                        mResolveInfo.priority = 0;
11210                        mResolveInfo.preferredOrder = 0;
11211                        mResolveInfo.match = 0;
11212                        mResolveComponentName = new ComponentName(
11213                                mAndroidApplication.packageName, mResolveActivity.name);
11214                    }
11215                }
11216            }
11217        }
11218
11219        ArrayList<PackageParser.Package> clientLibPkgs = null;
11220        // writer
11221        synchronized (mPackages) {
11222            boolean hasStaticSharedLibs = false;
11223
11224            // Any app can add new static shared libraries
11225            if (pkg.staticSharedLibName != null) {
11226                // Static shared libs don't allow renaming as they have synthetic package
11227                // names to allow install of multiple versions, so use name from manifest.
11228                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11229                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11230                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11231                    hasStaticSharedLibs = true;
11232                } else {
11233                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11234                                + pkg.staticSharedLibName + " already exists; skipping");
11235                }
11236                // Static shared libs cannot be updated once installed since they
11237                // use synthetic package name which includes the version code, so
11238                // not need to update other packages's shared lib dependencies.
11239            }
11240
11241            if (!hasStaticSharedLibs
11242                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11243                // Only system apps can add new dynamic shared libraries.
11244                if (pkg.libraryNames != null) {
11245                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11246                        String name = pkg.libraryNames.get(i);
11247                        boolean allowed = false;
11248                        if (pkg.isUpdatedSystemApp()) {
11249                            // New library entries can only be added through the
11250                            // system image.  This is important to get rid of a lot
11251                            // of nasty edge cases: for example if we allowed a non-
11252                            // system update of the app to add a library, then uninstalling
11253                            // the update would make the library go away, and assumptions
11254                            // we made such as through app install filtering would now
11255                            // have allowed apps on the device which aren't compatible
11256                            // with it.  Better to just have the restriction here, be
11257                            // conservative, and create many fewer cases that can negatively
11258                            // impact the user experience.
11259                            final PackageSetting sysPs = mSettings
11260                                    .getDisabledSystemPkgLPr(pkg.packageName);
11261                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11262                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11263                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11264                                        allowed = true;
11265                                        break;
11266                                    }
11267                                }
11268                            }
11269                        } else {
11270                            allowed = true;
11271                        }
11272                        if (allowed) {
11273                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11274                                    SharedLibraryInfo.VERSION_UNDEFINED,
11275                                    SharedLibraryInfo.TYPE_DYNAMIC,
11276                                    pkg.packageName, pkg.getLongVersionCode())) {
11277                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11278                                        + name + " already exists; skipping");
11279                            }
11280                        } else {
11281                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11282                                    + name + " that is not declared on system image; skipping");
11283                        }
11284                    }
11285
11286                    if ((scanFlags & SCAN_BOOTING) == 0) {
11287                        // If we are not booting, we need to update any applications
11288                        // that are clients of our shared library.  If we are booting,
11289                        // this will all be done once the scan is complete.
11290                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11291                    }
11292                }
11293            }
11294        }
11295
11296        if ((scanFlags & SCAN_BOOTING) != 0) {
11297            // No apps can run during boot scan, so they don't need to be frozen
11298        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11299            // Caller asked to not kill app, so it's probably not frozen
11300        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11301            // Caller asked us to ignore frozen check for some reason; they
11302            // probably didn't know the package name
11303        } else {
11304            // We're doing major surgery on this package, so it better be frozen
11305            // right now to keep it from launching
11306            checkPackageFrozen(pkgName);
11307        }
11308
11309        // Also need to kill any apps that are dependent on the library.
11310        if (clientLibPkgs != null) {
11311            for (int i=0; i<clientLibPkgs.size(); i++) {
11312                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11313                killApplication(clientPkg.applicationInfo.packageName,
11314                        clientPkg.applicationInfo.uid, "update lib");
11315            }
11316        }
11317
11318        // writer
11319        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11320
11321        synchronized (mPackages) {
11322            // We don't expect installation to fail beyond this point
11323
11324            // Add the new setting to mSettings
11325            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11326            // Add the new setting to mPackages
11327            mPackages.put(pkg.applicationInfo.packageName, pkg);
11328            // Make sure we don't accidentally delete its data.
11329            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11330            while (iter.hasNext()) {
11331                PackageCleanItem item = iter.next();
11332                if (pkgName.equals(item.packageName)) {
11333                    iter.remove();
11334                }
11335            }
11336
11337            // Add the package's KeySets to the global KeySetManagerService
11338            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11339            ksms.addScannedPackageLPw(pkg);
11340
11341            int N = pkg.providers.size();
11342            StringBuilder r = null;
11343            int i;
11344            for (i=0; i<N; i++) {
11345                PackageParser.Provider p = pkg.providers.get(i);
11346                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11347                        p.info.processName);
11348                mProviders.addProvider(p);
11349                p.syncable = p.info.isSyncable;
11350                if (p.info.authority != null) {
11351                    String names[] = p.info.authority.split(";");
11352                    p.info.authority = null;
11353                    for (int j = 0; j < names.length; j++) {
11354                        if (j == 1 && p.syncable) {
11355                            // We only want the first authority for a provider to possibly be
11356                            // syncable, so if we already added this provider using a different
11357                            // authority clear the syncable flag. We copy the provider before
11358                            // changing it because the mProviders object contains a reference
11359                            // to a provider that we don't want to change.
11360                            // Only do this for the second authority since the resulting provider
11361                            // object can be the same for all future authorities for this provider.
11362                            p = new PackageParser.Provider(p);
11363                            p.syncable = false;
11364                        }
11365                        if (!mProvidersByAuthority.containsKey(names[j])) {
11366                            mProvidersByAuthority.put(names[j], p);
11367                            if (p.info.authority == null) {
11368                                p.info.authority = names[j];
11369                            } else {
11370                                p.info.authority = p.info.authority + ";" + names[j];
11371                            }
11372                            if (DEBUG_PACKAGE_SCANNING) {
11373                                if (chatty)
11374                                    Log.d(TAG, "Registered content provider: " + names[j]
11375                                            + ", className = " + p.info.name + ", isSyncable = "
11376                                            + p.info.isSyncable);
11377                            }
11378                        } else {
11379                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11380                            Slog.w(TAG, "Skipping provider name " + names[j] +
11381                                    " (in package " + pkg.applicationInfo.packageName +
11382                                    "): name already used by "
11383                                    + ((other != null && other.getComponentName() != null)
11384                                            ? other.getComponentName().getPackageName() : "?"));
11385                        }
11386                    }
11387                }
11388                if (chatty) {
11389                    if (r == null) {
11390                        r = new StringBuilder(256);
11391                    } else {
11392                        r.append(' ');
11393                    }
11394                    r.append(p.info.name);
11395                }
11396            }
11397            if (r != null) {
11398                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11399            }
11400
11401            N = pkg.services.size();
11402            r = null;
11403            for (i=0; i<N; i++) {
11404                PackageParser.Service s = pkg.services.get(i);
11405                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11406                        s.info.processName);
11407                mServices.addService(s);
11408                if (chatty) {
11409                    if (r == null) {
11410                        r = new StringBuilder(256);
11411                    } else {
11412                        r.append(' ');
11413                    }
11414                    r.append(s.info.name);
11415                }
11416            }
11417            if (r != null) {
11418                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11419            }
11420
11421            N = pkg.receivers.size();
11422            r = null;
11423            for (i=0; i<N; i++) {
11424                PackageParser.Activity a = pkg.receivers.get(i);
11425                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11426                        a.info.processName);
11427                mReceivers.addActivity(a, "receiver");
11428                if (chatty) {
11429                    if (r == null) {
11430                        r = new StringBuilder(256);
11431                    } else {
11432                        r.append(' ');
11433                    }
11434                    r.append(a.info.name);
11435                }
11436            }
11437            if (r != null) {
11438                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11439            }
11440
11441            N = pkg.activities.size();
11442            r = null;
11443            for (i=0; i<N; i++) {
11444                PackageParser.Activity a = pkg.activities.get(i);
11445                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11446                        a.info.processName);
11447                mActivities.addActivity(a, "activity");
11448                if (chatty) {
11449                    if (r == null) {
11450                        r = new StringBuilder(256);
11451                    } else {
11452                        r.append(' ');
11453                    }
11454                    r.append(a.info.name);
11455                }
11456            }
11457            if (r != null) {
11458                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11459            }
11460
11461            // Don't allow ephemeral applications to define new permissions groups.
11462            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11463                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11464                        + " ignored: instant apps cannot define new permission groups.");
11465            } else {
11466                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11467            }
11468
11469            // Don't allow ephemeral applications to define new permissions.
11470            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11471                Slog.w(TAG, "Permissions from package " + pkg.packageName
11472                        + " ignored: instant apps cannot define new permissions.");
11473            } else {
11474                mPermissionManager.addAllPermissions(pkg, chatty);
11475            }
11476
11477            N = pkg.instrumentation.size();
11478            r = null;
11479            for (i=0; i<N; i++) {
11480                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11481                a.info.packageName = pkg.applicationInfo.packageName;
11482                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11483                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11484                a.info.splitNames = pkg.splitNames;
11485                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11486                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11487                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11488                a.info.dataDir = pkg.applicationInfo.dataDir;
11489                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11490                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11491                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11492                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11493                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11494                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11495                mInstrumentation.put(a.getComponentName(), a);
11496                if (chatty) {
11497                    if (r == null) {
11498                        r = new StringBuilder(256);
11499                    } else {
11500                        r.append(' ');
11501                    }
11502                    r.append(a.info.name);
11503                }
11504            }
11505            if (r != null) {
11506                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11507            }
11508
11509            if (pkg.protectedBroadcasts != null) {
11510                N = pkg.protectedBroadcasts.size();
11511                synchronized (mProtectedBroadcasts) {
11512                    for (i = 0; i < N; i++) {
11513                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11514                    }
11515                }
11516            }
11517
11518            if (oldPkg != null) {
11519                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11520                // revoke callbacks from this method might need to kill apps which need the
11521                // mPackages lock on a different thread. This would dead lock.
11522                //
11523                // Hence create a copy of all package names and pass it into
11524                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11525                // revoked. If a new package is added before the async code runs the permission
11526                // won't be granted yet, hence new packages are no problem.
11527                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11528
11529                AsyncTask.execute(() ->
11530                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11531                                allPackageNames, mPermissionCallback));
11532            }
11533        }
11534
11535        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11536    }
11537
11538    /**
11539     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11540     * is derived purely on the basis of the contents of {@code scanFile} and
11541     * {@code cpuAbiOverride}.
11542     *
11543     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11544     */
11545    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11546            boolean extractLibs)
11547                    throws PackageManagerException {
11548        // Give ourselves some initial paths; we'll come back for another
11549        // pass once we've determined ABI below.
11550        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11551
11552        // We would never need to extract libs for forward-locked and external packages,
11553        // since the container service will do it for us. We shouldn't attempt to
11554        // extract libs from system app when it was not updated.
11555        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11556                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11557            extractLibs = false;
11558        }
11559
11560        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11561        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11562
11563        NativeLibraryHelper.Handle handle = null;
11564        try {
11565            handle = NativeLibraryHelper.Handle.create(pkg);
11566            // TODO(multiArch): This can be null for apps that didn't go through the
11567            // usual installation process. We can calculate it again, like we
11568            // do during install time.
11569            //
11570            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11571            // unnecessary.
11572            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11573
11574            // Null out the abis so that they can be recalculated.
11575            pkg.applicationInfo.primaryCpuAbi = null;
11576            pkg.applicationInfo.secondaryCpuAbi = null;
11577            if (isMultiArch(pkg.applicationInfo)) {
11578                // Warn if we've set an abiOverride for multi-lib packages..
11579                // By definition, we need to copy both 32 and 64 bit libraries for
11580                // such packages.
11581                if (pkg.cpuAbiOverride != null
11582                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11583                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11584                }
11585
11586                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11587                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11588                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11589                    if (extractLibs) {
11590                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11591                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11592                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11593                                useIsaSpecificSubdirs);
11594                    } else {
11595                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11596                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11597                    }
11598                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11599                }
11600
11601                // Shared library native code should be in the APK zip aligned
11602                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11603                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11604                            "Shared library native lib extraction not supported");
11605                }
11606
11607                maybeThrowExceptionForMultiArchCopy(
11608                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11609
11610                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11611                    if (extractLibs) {
11612                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11613                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11614                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11615                                useIsaSpecificSubdirs);
11616                    } else {
11617                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11618                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11619                    }
11620                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11621                }
11622
11623                maybeThrowExceptionForMultiArchCopy(
11624                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11625
11626                if (abi64 >= 0) {
11627                    // Shared library native libs should be in the APK zip aligned
11628                    if (extractLibs && pkg.isLibrary()) {
11629                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11630                                "Shared library native lib extraction not supported");
11631                    }
11632                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11633                }
11634
11635                if (abi32 >= 0) {
11636                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11637                    if (abi64 >= 0) {
11638                        if (pkg.use32bitAbi) {
11639                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11640                            pkg.applicationInfo.primaryCpuAbi = abi;
11641                        } else {
11642                            pkg.applicationInfo.secondaryCpuAbi = abi;
11643                        }
11644                    } else {
11645                        pkg.applicationInfo.primaryCpuAbi = abi;
11646                    }
11647                }
11648            } else {
11649                String[] abiList = (cpuAbiOverride != null) ?
11650                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11651
11652                // Enable gross and lame hacks for apps that are built with old
11653                // SDK tools. We must scan their APKs for renderscript bitcode and
11654                // not launch them if it's present. Don't bother checking on devices
11655                // that don't have 64 bit support.
11656                boolean needsRenderScriptOverride = false;
11657                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11658                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11659                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11660                    needsRenderScriptOverride = true;
11661                }
11662
11663                final int copyRet;
11664                if (extractLibs) {
11665                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11666                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11667                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11668                } else {
11669                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11670                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11671                }
11672                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11673
11674                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11675                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11676                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11677                }
11678
11679                if (copyRet >= 0) {
11680                    // Shared libraries that have native libs must be multi-architecture
11681                    if (pkg.isLibrary()) {
11682                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11683                                "Shared library with native libs must be multiarch");
11684                    }
11685                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11686                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11687                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11688                } else if (needsRenderScriptOverride) {
11689                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11690                }
11691            }
11692        } catch (IOException ioe) {
11693            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11694        } finally {
11695            IoUtils.closeQuietly(handle);
11696        }
11697
11698        // Now that we've calculated the ABIs and determined if it's an internal app,
11699        // we will go ahead and populate the nativeLibraryPath.
11700        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11701    }
11702
11703    /**
11704     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11705     * i.e, so that all packages can be run inside a single process if required.
11706     *
11707     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11708     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11709     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11710     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11711     * updating a package that belongs to a shared user.
11712     *
11713     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11714     * adds unnecessary complexity.
11715     */
11716    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11717            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11718        List<String> changedAbiCodePath = null;
11719        String requiredInstructionSet = null;
11720        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11721            requiredInstructionSet = VMRuntime.getInstructionSet(
11722                     scannedPackage.applicationInfo.primaryCpuAbi);
11723        }
11724
11725        PackageSetting requirer = null;
11726        for (PackageSetting ps : packagesForUser) {
11727            // If packagesForUser contains scannedPackage, we skip it. This will happen
11728            // when scannedPackage is an update of an existing package. Without this check,
11729            // we will never be able to change the ABI of any package belonging to a shared
11730            // user, even if it's compatible with other packages.
11731            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11732                if (ps.primaryCpuAbiString == null) {
11733                    continue;
11734                }
11735
11736                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11737                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11738                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11739                    // this but there's not much we can do.
11740                    String errorMessage = "Instruction set mismatch, "
11741                            + ((requirer == null) ? "[caller]" : requirer)
11742                            + " requires " + requiredInstructionSet + " whereas " + ps
11743                            + " requires " + instructionSet;
11744                    Slog.w(TAG, errorMessage);
11745                }
11746
11747                if (requiredInstructionSet == null) {
11748                    requiredInstructionSet = instructionSet;
11749                    requirer = ps;
11750                }
11751            }
11752        }
11753
11754        if (requiredInstructionSet != null) {
11755            String adjustedAbi;
11756            if (requirer != null) {
11757                // requirer != null implies that either scannedPackage was null or that scannedPackage
11758                // did not require an ABI, in which case we have to adjust scannedPackage to match
11759                // the ABI of the set (which is the same as requirer's ABI)
11760                adjustedAbi = requirer.primaryCpuAbiString;
11761                if (scannedPackage != null) {
11762                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11763                }
11764            } else {
11765                // requirer == null implies that we're updating all ABIs in the set to
11766                // match scannedPackage.
11767                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11768            }
11769
11770            for (PackageSetting ps : packagesForUser) {
11771                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11772                    if (ps.primaryCpuAbiString != null) {
11773                        continue;
11774                    }
11775
11776                    ps.primaryCpuAbiString = adjustedAbi;
11777                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11778                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11779                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11780                        if (DEBUG_ABI_SELECTION) {
11781                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11782                                    + " (requirer="
11783                                    + (requirer != null ? requirer.pkg : "null")
11784                                    + ", scannedPackage="
11785                                    + (scannedPackage != null ? scannedPackage : "null")
11786                                    + ")");
11787                        }
11788                        if (changedAbiCodePath == null) {
11789                            changedAbiCodePath = new ArrayList<>();
11790                        }
11791                        changedAbiCodePath.add(ps.codePathString);
11792                    }
11793                }
11794            }
11795        }
11796        return changedAbiCodePath;
11797    }
11798
11799    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11800        synchronized (mPackages) {
11801            mResolverReplaced = true;
11802            // Set up information for custom user intent resolution activity.
11803            mResolveActivity.applicationInfo = pkg.applicationInfo;
11804            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11805            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11806            mResolveActivity.processName = pkg.applicationInfo.packageName;
11807            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11808            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11809                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11810            mResolveActivity.theme = 0;
11811            mResolveActivity.exported = true;
11812            mResolveActivity.enabled = true;
11813            mResolveInfo.activityInfo = mResolveActivity;
11814            mResolveInfo.priority = 0;
11815            mResolveInfo.preferredOrder = 0;
11816            mResolveInfo.match = 0;
11817            mResolveComponentName = mCustomResolverComponentName;
11818            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11819                    mResolveComponentName);
11820        }
11821    }
11822
11823    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11824        if (installerActivity == null) {
11825            if (DEBUG_INSTANT) {
11826                Slog.d(TAG, "Clear ephemeral installer activity");
11827            }
11828            mInstantAppInstallerActivity = null;
11829            return;
11830        }
11831
11832        if (DEBUG_INSTANT) {
11833            Slog.d(TAG, "Set ephemeral installer activity: "
11834                    + installerActivity.getComponentName());
11835        }
11836        // Set up information for ephemeral installer activity
11837        mInstantAppInstallerActivity = installerActivity;
11838        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11839                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11840        mInstantAppInstallerActivity.exported = true;
11841        mInstantAppInstallerActivity.enabled = true;
11842        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11843        mInstantAppInstallerInfo.priority = 1;
11844        mInstantAppInstallerInfo.preferredOrder = 1;
11845        mInstantAppInstallerInfo.isDefault = true;
11846        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11847                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11848    }
11849
11850    private static String calculateBundledApkRoot(final String codePathString) {
11851        final File codePath = new File(codePathString);
11852        final File codeRoot;
11853        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11854            codeRoot = Environment.getRootDirectory();
11855        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11856            codeRoot = Environment.getOemDirectory();
11857        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11858            codeRoot = Environment.getVendorDirectory();
11859        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11860            codeRoot = Environment.getOdmDirectory();
11861        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11862            codeRoot = Environment.getProductDirectory();
11863        } else {
11864            // Unrecognized code path; take its top real segment as the apk root:
11865            // e.g. /something/app/blah.apk => /something
11866            try {
11867                File f = codePath.getCanonicalFile();
11868                File parent = f.getParentFile();    // non-null because codePath is a file
11869                File tmp;
11870                while ((tmp = parent.getParentFile()) != null) {
11871                    f = parent;
11872                    parent = tmp;
11873                }
11874                codeRoot = f;
11875                Slog.w(TAG, "Unrecognized code path "
11876                        + codePath + " - using " + codeRoot);
11877            } catch (IOException e) {
11878                // Can't canonicalize the code path -- shenanigans?
11879                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11880                return Environment.getRootDirectory().getPath();
11881            }
11882        }
11883        return codeRoot.getPath();
11884    }
11885
11886    /**
11887     * Derive and set the location of native libraries for the given package,
11888     * which varies depending on where and how the package was installed.
11889     */
11890    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11891        final ApplicationInfo info = pkg.applicationInfo;
11892        final String codePath = pkg.codePath;
11893        final File codeFile = new File(codePath);
11894        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11895        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11896
11897        info.nativeLibraryRootDir = null;
11898        info.nativeLibraryRootRequiresIsa = false;
11899        info.nativeLibraryDir = null;
11900        info.secondaryNativeLibraryDir = null;
11901
11902        if (isApkFile(codeFile)) {
11903            // Monolithic install
11904            if (bundledApp) {
11905                // If "/system/lib64/apkname" exists, assume that is the per-package
11906                // native library directory to use; otherwise use "/system/lib/apkname".
11907                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11908                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11909                        getPrimaryInstructionSet(info));
11910
11911                // This is a bundled system app so choose the path based on the ABI.
11912                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11913                // is just the default path.
11914                final String apkName = deriveCodePathName(codePath);
11915                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11916                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11917                        apkName).getAbsolutePath();
11918
11919                if (info.secondaryCpuAbi != null) {
11920                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11921                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11922                            secondaryLibDir, apkName).getAbsolutePath();
11923                }
11924            } else if (asecApp) {
11925                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11926                        .getAbsolutePath();
11927            } else {
11928                final String apkName = deriveCodePathName(codePath);
11929                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11930                        .getAbsolutePath();
11931            }
11932
11933            info.nativeLibraryRootRequiresIsa = false;
11934            info.nativeLibraryDir = info.nativeLibraryRootDir;
11935        } else {
11936            // Cluster install
11937            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11938            info.nativeLibraryRootRequiresIsa = true;
11939
11940            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11941                    getPrimaryInstructionSet(info)).getAbsolutePath();
11942
11943            if (info.secondaryCpuAbi != null) {
11944                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11945                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11946            }
11947        }
11948    }
11949
11950    /**
11951     * Calculate the abis and roots for a bundled app. These can uniquely
11952     * be determined from the contents of the system partition, i.e whether
11953     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11954     * of this information, and instead assume that the system was built
11955     * sensibly.
11956     */
11957    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11958                                           PackageSetting pkgSetting) {
11959        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11960
11961        // If "/system/lib64/apkname" exists, assume that is the per-package
11962        // native library directory to use; otherwise use "/system/lib/apkname".
11963        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11964        setBundledAppAbi(pkg, apkRoot, apkName);
11965        // pkgSetting might be null during rescan following uninstall of updates
11966        // to a bundled app, so accommodate that possibility.  The settings in
11967        // that case will be established later from the parsed package.
11968        //
11969        // If the settings aren't null, sync them up with what we've just derived.
11970        // note that apkRoot isn't stored in the package settings.
11971        if (pkgSetting != null) {
11972            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11973            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11974        }
11975    }
11976
11977    /**
11978     * Deduces the ABI of a bundled app and sets the relevant fields on the
11979     * parsed pkg object.
11980     *
11981     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11982     *        under which system libraries are installed.
11983     * @param apkName the name of the installed package.
11984     */
11985    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11986        final File codeFile = new File(pkg.codePath);
11987
11988        final boolean has64BitLibs;
11989        final boolean has32BitLibs;
11990        if (isApkFile(codeFile)) {
11991            // Monolithic install
11992            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11993            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11994        } else {
11995            // Cluster install
11996            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11997            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11998                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11999                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12000                has64BitLibs = (new File(rootDir, isa)).exists();
12001            } else {
12002                has64BitLibs = false;
12003            }
12004            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12005                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12006                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12007                has32BitLibs = (new File(rootDir, isa)).exists();
12008            } else {
12009                has32BitLibs = false;
12010            }
12011        }
12012
12013        if (has64BitLibs && !has32BitLibs) {
12014            // The package has 64 bit libs, but not 32 bit libs. Its primary
12015            // ABI should be 64 bit. We can safely assume here that the bundled
12016            // native libraries correspond to the most preferred ABI in the list.
12017
12018            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12019            pkg.applicationInfo.secondaryCpuAbi = null;
12020        } else if (has32BitLibs && !has64BitLibs) {
12021            // The package has 32 bit libs but not 64 bit libs. Its primary
12022            // ABI should be 32 bit.
12023
12024            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12025            pkg.applicationInfo.secondaryCpuAbi = null;
12026        } else if (has32BitLibs && has64BitLibs) {
12027            // The application has both 64 and 32 bit bundled libraries. We check
12028            // here that the app declares multiArch support, and warn if it doesn't.
12029            //
12030            // We will be lenient here and record both ABIs. The primary will be the
12031            // ABI that's higher on the list, i.e, a device that's configured to prefer
12032            // 64 bit apps will see a 64 bit primary ABI,
12033
12034            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12035                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12036            }
12037
12038            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12039                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12040                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12041            } else {
12042                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12043                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12044            }
12045        } else {
12046            pkg.applicationInfo.primaryCpuAbi = null;
12047            pkg.applicationInfo.secondaryCpuAbi = null;
12048        }
12049    }
12050
12051    private void killApplication(String pkgName, int appId, String reason) {
12052        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12053    }
12054
12055    private void killApplication(String pkgName, int appId, int userId, String reason) {
12056        // Request the ActivityManager to kill the process(only for existing packages)
12057        // so that we do not end up in a confused state while the user is still using the older
12058        // version of the application while the new one gets installed.
12059        final long token = Binder.clearCallingIdentity();
12060        try {
12061            IActivityManager am = ActivityManager.getService();
12062            if (am != null) {
12063                try {
12064                    am.killApplication(pkgName, appId, userId, reason);
12065                } catch (RemoteException e) {
12066                }
12067            }
12068        } finally {
12069            Binder.restoreCallingIdentity(token);
12070        }
12071    }
12072
12073    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12074        // Remove the parent package setting
12075        PackageSetting ps = (PackageSetting) pkg.mExtras;
12076        if (ps != null) {
12077            removePackageLI(ps, chatty);
12078        }
12079        // Remove the child package setting
12080        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12081        for (int i = 0; i < childCount; i++) {
12082            PackageParser.Package childPkg = pkg.childPackages.get(i);
12083            ps = (PackageSetting) childPkg.mExtras;
12084            if (ps != null) {
12085                removePackageLI(ps, chatty);
12086            }
12087        }
12088    }
12089
12090    void removePackageLI(PackageSetting ps, boolean chatty) {
12091        if (DEBUG_INSTALL) {
12092            if (chatty)
12093                Log.d(TAG, "Removing package " + ps.name);
12094        }
12095
12096        // writer
12097        synchronized (mPackages) {
12098            mPackages.remove(ps.name);
12099            final PackageParser.Package pkg = ps.pkg;
12100            if (pkg != null) {
12101                cleanPackageDataStructuresLILPw(pkg, chatty);
12102            }
12103        }
12104    }
12105
12106    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12107        if (DEBUG_INSTALL) {
12108            if (chatty)
12109                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12110        }
12111
12112        // writer
12113        synchronized (mPackages) {
12114            // Remove the parent package
12115            mPackages.remove(pkg.applicationInfo.packageName);
12116            cleanPackageDataStructuresLILPw(pkg, chatty);
12117
12118            // Remove the child packages
12119            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12120            for (int i = 0; i < childCount; i++) {
12121                PackageParser.Package childPkg = pkg.childPackages.get(i);
12122                mPackages.remove(childPkg.applicationInfo.packageName);
12123                cleanPackageDataStructuresLILPw(childPkg, chatty);
12124            }
12125        }
12126    }
12127
12128    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12129        int N = pkg.providers.size();
12130        StringBuilder r = null;
12131        int i;
12132        for (i=0; i<N; i++) {
12133            PackageParser.Provider p = pkg.providers.get(i);
12134            mProviders.removeProvider(p);
12135            if (p.info.authority == null) {
12136
12137                /* There was another ContentProvider with this authority when
12138                 * this app was installed so this authority is null,
12139                 * Ignore it as we don't have to unregister the provider.
12140                 */
12141                continue;
12142            }
12143            String names[] = p.info.authority.split(";");
12144            for (int j = 0; j < names.length; j++) {
12145                if (mProvidersByAuthority.get(names[j]) == p) {
12146                    mProvidersByAuthority.remove(names[j]);
12147                    if (DEBUG_REMOVE) {
12148                        if (chatty)
12149                            Log.d(TAG, "Unregistered content provider: " + names[j]
12150                                    + ", className = " + p.info.name + ", isSyncable = "
12151                                    + p.info.isSyncable);
12152                    }
12153                }
12154            }
12155            if (DEBUG_REMOVE && chatty) {
12156                if (r == null) {
12157                    r = new StringBuilder(256);
12158                } else {
12159                    r.append(' ');
12160                }
12161                r.append(p.info.name);
12162            }
12163        }
12164        if (r != null) {
12165            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12166        }
12167
12168        N = pkg.services.size();
12169        r = null;
12170        for (i=0; i<N; i++) {
12171            PackageParser.Service s = pkg.services.get(i);
12172            mServices.removeService(s);
12173            if (chatty) {
12174                if (r == null) {
12175                    r = new StringBuilder(256);
12176                } else {
12177                    r.append(' ');
12178                }
12179                r.append(s.info.name);
12180            }
12181        }
12182        if (r != null) {
12183            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12184        }
12185
12186        N = pkg.receivers.size();
12187        r = null;
12188        for (i=0; i<N; i++) {
12189            PackageParser.Activity a = pkg.receivers.get(i);
12190            mReceivers.removeActivity(a, "receiver");
12191            if (DEBUG_REMOVE && chatty) {
12192                if (r == null) {
12193                    r = new StringBuilder(256);
12194                } else {
12195                    r.append(' ');
12196                }
12197                r.append(a.info.name);
12198            }
12199        }
12200        if (r != null) {
12201            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12202        }
12203
12204        N = pkg.activities.size();
12205        r = null;
12206        for (i=0; i<N; i++) {
12207            PackageParser.Activity a = pkg.activities.get(i);
12208            mActivities.removeActivity(a, "activity");
12209            if (DEBUG_REMOVE && chatty) {
12210                if (r == null) {
12211                    r = new StringBuilder(256);
12212                } else {
12213                    r.append(' ');
12214                }
12215                r.append(a.info.name);
12216            }
12217        }
12218        if (r != null) {
12219            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12220        }
12221
12222        mPermissionManager.removeAllPermissions(pkg, chatty);
12223
12224        N = pkg.instrumentation.size();
12225        r = null;
12226        for (i=0; i<N; i++) {
12227            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12228            mInstrumentation.remove(a.getComponentName());
12229            if (DEBUG_REMOVE && chatty) {
12230                if (r == null) {
12231                    r = new StringBuilder(256);
12232                } else {
12233                    r.append(' ');
12234                }
12235                r.append(a.info.name);
12236            }
12237        }
12238        if (r != null) {
12239            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12240        }
12241
12242        r = null;
12243        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12244            // Only system apps can hold shared libraries.
12245            if (pkg.libraryNames != null) {
12246                for (i = 0; i < pkg.libraryNames.size(); i++) {
12247                    String name = pkg.libraryNames.get(i);
12248                    if (removeSharedLibraryLPw(name, 0)) {
12249                        if (DEBUG_REMOVE && chatty) {
12250                            if (r == null) {
12251                                r = new StringBuilder(256);
12252                            } else {
12253                                r.append(' ');
12254                            }
12255                            r.append(name);
12256                        }
12257                    }
12258                }
12259            }
12260        }
12261
12262        r = null;
12263
12264        // Any package can hold static shared libraries.
12265        if (pkg.staticSharedLibName != null) {
12266            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12267                if (DEBUG_REMOVE && chatty) {
12268                    if (r == null) {
12269                        r = new StringBuilder(256);
12270                    } else {
12271                        r.append(' ');
12272                    }
12273                    r.append(pkg.staticSharedLibName);
12274                }
12275            }
12276        }
12277
12278        if (r != null) {
12279            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12280        }
12281    }
12282
12283
12284    final class ActivityIntentResolver
12285            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12286        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12287                boolean defaultOnly, int userId) {
12288            if (!sUserManager.exists(userId)) return null;
12289            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12290            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12291        }
12292
12293        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12294                int userId) {
12295            if (!sUserManager.exists(userId)) return null;
12296            mFlags = flags;
12297            return super.queryIntent(intent, resolvedType,
12298                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12299                    userId);
12300        }
12301
12302        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12303                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12304            if (!sUserManager.exists(userId)) return null;
12305            if (packageActivities == null) {
12306                return null;
12307            }
12308            mFlags = flags;
12309            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12310            final int N = packageActivities.size();
12311            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12312                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12313
12314            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12315            for (int i = 0; i < N; ++i) {
12316                intentFilters = packageActivities.get(i).intents;
12317                if (intentFilters != null && intentFilters.size() > 0) {
12318                    PackageParser.ActivityIntentInfo[] array =
12319                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12320                    intentFilters.toArray(array);
12321                    listCut.add(array);
12322                }
12323            }
12324            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12325        }
12326
12327        /**
12328         * Finds a privileged activity that matches the specified activity names.
12329         */
12330        private PackageParser.Activity findMatchingActivity(
12331                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12332            for (PackageParser.Activity sysActivity : activityList) {
12333                if (sysActivity.info.name.equals(activityInfo.name)) {
12334                    return sysActivity;
12335                }
12336                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12337                    return sysActivity;
12338                }
12339                if (sysActivity.info.targetActivity != null) {
12340                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12341                        return sysActivity;
12342                    }
12343                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12344                        return sysActivity;
12345                    }
12346                }
12347            }
12348            return null;
12349        }
12350
12351        public class IterGenerator<E> {
12352            public Iterator<E> generate(ActivityIntentInfo info) {
12353                return null;
12354            }
12355        }
12356
12357        public class ActionIterGenerator extends IterGenerator<String> {
12358            @Override
12359            public Iterator<String> generate(ActivityIntentInfo info) {
12360                return info.actionsIterator();
12361            }
12362        }
12363
12364        public class CategoriesIterGenerator extends IterGenerator<String> {
12365            @Override
12366            public Iterator<String> generate(ActivityIntentInfo info) {
12367                return info.categoriesIterator();
12368            }
12369        }
12370
12371        public class SchemesIterGenerator extends IterGenerator<String> {
12372            @Override
12373            public Iterator<String> generate(ActivityIntentInfo info) {
12374                return info.schemesIterator();
12375            }
12376        }
12377
12378        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12379            @Override
12380            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12381                return info.authoritiesIterator();
12382            }
12383        }
12384
12385        /**
12386         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12387         * MODIFIED. Do not pass in a list that should not be changed.
12388         */
12389        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12390                IterGenerator<T> generator, Iterator<T> searchIterator) {
12391            // loop through the set of actions; every one must be found in the intent filter
12392            while (searchIterator.hasNext()) {
12393                // we must have at least one filter in the list to consider a match
12394                if (intentList.size() == 0) {
12395                    break;
12396                }
12397
12398                final T searchAction = searchIterator.next();
12399
12400                // loop through the set of intent filters
12401                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12402                while (intentIter.hasNext()) {
12403                    final ActivityIntentInfo intentInfo = intentIter.next();
12404                    boolean selectionFound = false;
12405
12406                    // loop through the intent filter's selection criteria; at least one
12407                    // of them must match the searched criteria
12408                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12409                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12410                        final T intentSelection = intentSelectionIter.next();
12411                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12412                            selectionFound = true;
12413                            break;
12414                        }
12415                    }
12416
12417                    // the selection criteria wasn't found in this filter's set; this filter
12418                    // is not a potential match
12419                    if (!selectionFound) {
12420                        intentIter.remove();
12421                    }
12422                }
12423            }
12424        }
12425
12426        private boolean isProtectedAction(ActivityIntentInfo filter) {
12427            final Iterator<String> actionsIter = filter.actionsIterator();
12428            while (actionsIter != null && actionsIter.hasNext()) {
12429                final String filterAction = actionsIter.next();
12430                if (PROTECTED_ACTIONS.contains(filterAction)) {
12431                    return true;
12432                }
12433            }
12434            return false;
12435        }
12436
12437        /**
12438         * Adjusts the priority of the given intent filter according to policy.
12439         * <p>
12440         * <ul>
12441         * <li>The priority for non privileged applications is capped to '0'</li>
12442         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12443         * <li>The priority for unbundled updates to privileged applications is capped to the
12444         *      priority defined on the system partition</li>
12445         * </ul>
12446         * <p>
12447         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12448         * allowed to obtain any priority on any action.
12449         */
12450        private void adjustPriority(
12451                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12452            // nothing to do; priority is fine as-is
12453            if (intent.getPriority() <= 0) {
12454                return;
12455            }
12456
12457            final ActivityInfo activityInfo = intent.activity.info;
12458            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12459
12460            final boolean privilegedApp =
12461                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12462            if (!privilegedApp) {
12463                // non-privileged applications can never define a priority >0
12464                if (DEBUG_FILTERS) {
12465                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12466                            + " package: " + applicationInfo.packageName
12467                            + " activity: " + intent.activity.className
12468                            + " origPrio: " + intent.getPriority());
12469                }
12470                intent.setPriority(0);
12471                return;
12472            }
12473
12474            if (systemActivities == null) {
12475                // the system package is not disabled; we're parsing the system partition
12476                if (isProtectedAction(intent)) {
12477                    if (mDeferProtectedFilters) {
12478                        // We can't deal with these just yet. No component should ever obtain a
12479                        // >0 priority for a protected actions, with ONE exception -- the setup
12480                        // wizard. The setup wizard, however, cannot be known until we're able to
12481                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12482                        // until all intent filters have been processed. Chicken, meet egg.
12483                        // Let the filter temporarily have a high priority and rectify the
12484                        // priorities after all system packages have been scanned.
12485                        mProtectedFilters.add(intent);
12486                        if (DEBUG_FILTERS) {
12487                            Slog.i(TAG, "Protected action; save for later;"
12488                                    + " package: " + applicationInfo.packageName
12489                                    + " activity: " + intent.activity.className
12490                                    + " origPrio: " + intent.getPriority());
12491                        }
12492                        return;
12493                    } else {
12494                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12495                            Slog.i(TAG, "No setup wizard;"
12496                                + " All protected intents capped to priority 0");
12497                        }
12498                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12499                            if (DEBUG_FILTERS) {
12500                                Slog.i(TAG, "Found setup wizard;"
12501                                    + " allow priority " + intent.getPriority() + ";"
12502                                    + " package: " + intent.activity.info.packageName
12503                                    + " activity: " + intent.activity.className
12504                                    + " priority: " + intent.getPriority());
12505                            }
12506                            // setup wizard gets whatever it wants
12507                            return;
12508                        }
12509                        if (DEBUG_FILTERS) {
12510                            Slog.i(TAG, "Protected action; cap priority to 0;"
12511                                    + " package: " + intent.activity.info.packageName
12512                                    + " activity: " + intent.activity.className
12513                                    + " origPrio: " + intent.getPriority());
12514                        }
12515                        intent.setPriority(0);
12516                        return;
12517                    }
12518                }
12519                // privileged apps on the system image get whatever priority they request
12520                return;
12521            }
12522
12523            // privileged app unbundled update ... try to find the same activity
12524            final PackageParser.Activity foundActivity =
12525                    findMatchingActivity(systemActivities, activityInfo);
12526            if (foundActivity == null) {
12527                // this is a new activity; it cannot obtain >0 priority
12528                if (DEBUG_FILTERS) {
12529                    Slog.i(TAG, "New activity; cap priority to 0;"
12530                            + " package: " + applicationInfo.packageName
12531                            + " activity: " + intent.activity.className
12532                            + " origPrio: " + intent.getPriority());
12533                }
12534                intent.setPriority(0);
12535                return;
12536            }
12537
12538            // found activity, now check for filter equivalence
12539
12540            // a shallow copy is enough; we modify the list, not its contents
12541            final List<ActivityIntentInfo> intentListCopy =
12542                    new ArrayList<>(foundActivity.intents);
12543            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12544
12545            // find matching action subsets
12546            final Iterator<String> actionsIterator = intent.actionsIterator();
12547            if (actionsIterator != null) {
12548                getIntentListSubset(
12549                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12550                if (intentListCopy.size() == 0) {
12551                    // no more intents to match; we're not equivalent
12552                    if (DEBUG_FILTERS) {
12553                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12554                                + " package: " + applicationInfo.packageName
12555                                + " activity: " + intent.activity.className
12556                                + " origPrio: " + intent.getPriority());
12557                    }
12558                    intent.setPriority(0);
12559                    return;
12560                }
12561            }
12562
12563            // find matching category subsets
12564            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12565            if (categoriesIterator != null) {
12566                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12567                        categoriesIterator);
12568                if (intentListCopy.size() == 0) {
12569                    // no more intents to match; we're not equivalent
12570                    if (DEBUG_FILTERS) {
12571                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12572                                + " package: " + applicationInfo.packageName
12573                                + " activity: " + intent.activity.className
12574                                + " origPrio: " + intent.getPriority());
12575                    }
12576                    intent.setPriority(0);
12577                    return;
12578                }
12579            }
12580
12581            // find matching schemes subsets
12582            final Iterator<String> schemesIterator = intent.schemesIterator();
12583            if (schemesIterator != null) {
12584                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12585                        schemesIterator);
12586                if (intentListCopy.size() == 0) {
12587                    // no more intents to match; we're not equivalent
12588                    if (DEBUG_FILTERS) {
12589                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12590                                + " package: " + applicationInfo.packageName
12591                                + " activity: " + intent.activity.className
12592                                + " origPrio: " + intent.getPriority());
12593                    }
12594                    intent.setPriority(0);
12595                    return;
12596                }
12597            }
12598
12599            // find matching authorities subsets
12600            final Iterator<IntentFilter.AuthorityEntry>
12601                    authoritiesIterator = intent.authoritiesIterator();
12602            if (authoritiesIterator != null) {
12603                getIntentListSubset(intentListCopy,
12604                        new AuthoritiesIterGenerator(),
12605                        authoritiesIterator);
12606                if (intentListCopy.size() == 0) {
12607                    // no more intents to match; we're not equivalent
12608                    if (DEBUG_FILTERS) {
12609                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12610                                + " package: " + applicationInfo.packageName
12611                                + " activity: " + intent.activity.className
12612                                + " origPrio: " + intent.getPriority());
12613                    }
12614                    intent.setPriority(0);
12615                    return;
12616                }
12617            }
12618
12619            // we found matching filter(s); app gets the max priority of all intents
12620            int cappedPriority = 0;
12621            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12622                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12623            }
12624            if (intent.getPriority() > cappedPriority) {
12625                if (DEBUG_FILTERS) {
12626                    Slog.i(TAG, "Found matching filter(s);"
12627                            + " cap priority to " + cappedPriority + ";"
12628                            + " package: " + applicationInfo.packageName
12629                            + " activity: " + intent.activity.className
12630                            + " origPrio: " + intent.getPriority());
12631                }
12632                intent.setPriority(cappedPriority);
12633                return;
12634            }
12635            // all this for nothing; the requested priority was <= what was on the system
12636        }
12637
12638        public final void addActivity(PackageParser.Activity a, String type) {
12639            mActivities.put(a.getComponentName(), a);
12640            if (DEBUG_SHOW_INFO)
12641                Log.v(
12642                TAG, "  " + type + " " +
12643                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12644            if (DEBUG_SHOW_INFO)
12645                Log.v(TAG, "    Class=" + a.info.name);
12646            final int NI = a.intents.size();
12647            for (int j=0; j<NI; j++) {
12648                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12649                if ("activity".equals(type)) {
12650                    final PackageSetting ps =
12651                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12652                    final List<PackageParser.Activity> systemActivities =
12653                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12654                    adjustPriority(systemActivities, intent);
12655                }
12656                if (DEBUG_SHOW_INFO) {
12657                    Log.v(TAG, "    IntentFilter:");
12658                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12659                }
12660                if (!intent.debugCheck()) {
12661                    Log.w(TAG, "==> For Activity " + a.info.name);
12662                }
12663                addFilter(intent);
12664            }
12665        }
12666
12667        public final void removeActivity(PackageParser.Activity a, String type) {
12668            mActivities.remove(a.getComponentName());
12669            if (DEBUG_SHOW_INFO) {
12670                Log.v(TAG, "  " + type + " "
12671                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12672                                : a.info.name) + ":");
12673                Log.v(TAG, "    Class=" + a.info.name);
12674            }
12675            final int NI = a.intents.size();
12676            for (int j=0; j<NI; j++) {
12677                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12678                if (DEBUG_SHOW_INFO) {
12679                    Log.v(TAG, "    IntentFilter:");
12680                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12681                }
12682                removeFilter(intent);
12683            }
12684        }
12685
12686        @Override
12687        protected boolean allowFilterResult(
12688                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12689            ActivityInfo filterAi = filter.activity.info;
12690            for (int i=dest.size()-1; i>=0; i--) {
12691                ActivityInfo destAi = dest.get(i).activityInfo;
12692                if (destAi.name == filterAi.name
12693                        && destAi.packageName == filterAi.packageName) {
12694                    return false;
12695                }
12696            }
12697            return true;
12698        }
12699
12700        @Override
12701        protected ActivityIntentInfo[] newArray(int size) {
12702            return new ActivityIntentInfo[size];
12703        }
12704
12705        @Override
12706        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12707            if (!sUserManager.exists(userId)) return true;
12708            PackageParser.Package p = filter.activity.owner;
12709            if (p != null) {
12710                PackageSetting ps = (PackageSetting)p.mExtras;
12711                if (ps != null) {
12712                    // System apps are never considered stopped for purposes of
12713                    // filtering, because there may be no way for the user to
12714                    // actually re-launch them.
12715                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12716                            && ps.getStopped(userId);
12717                }
12718            }
12719            return false;
12720        }
12721
12722        @Override
12723        protected boolean isPackageForFilter(String packageName,
12724                PackageParser.ActivityIntentInfo info) {
12725            return packageName.equals(info.activity.owner.packageName);
12726        }
12727
12728        @Override
12729        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12730                int match, int userId) {
12731            if (!sUserManager.exists(userId)) return null;
12732            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12733                return null;
12734            }
12735            final PackageParser.Activity activity = info.activity;
12736            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12737            if (ps == null) {
12738                return null;
12739            }
12740            final PackageUserState userState = ps.readUserState(userId);
12741            ActivityInfo ai =
12742                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12743            if (ai == null) {
12744                return null;
12745            }
12746            final boolean matchExplicitlyVisibleOnly =
12747                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12748            final boolean matchVisibleToInstantApp =
12749                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12750            final boolean componentVisible =
12751                    matchVisibleToInstantApp
12752                    && info.isVisibleToInstantApp()
12753                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12754            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12755            // throw out filters that aren't visible to ephemeral apps
12756            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12757                return null;
12758            }
12759            // throw out instant app filters if we're not explicitly requesting them
12760            if (!matchInstantApp && userState.instantApp) {
12761                return null;
12762            }
12763            // throw out instant app filters if updates are available; will trigger
12764            // instant app resolution
12765            if (userState.instantApp && ps.isUpdateAvailable()) {
12766                return null;
12767            }
12768            final ResolveInfo res = new ResolveInfo();
12769            res.activityInfo = ai;
12770            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12771                res.filter = info;
12772            }
12773            if (info != null) {
12774                res.handleAllWebDataURI = info.handleAllWebDataURI();
12775            }
12776            res.priority = info.getPriority();
12777            res.preferredOrder = activity.owner.mPreferredOrder;
12778            //System.out.println("Result: " + res.activityInfo.className +
12779            //                   " = " + res.priority);
12780            res.match = match;
12781            res.isDefault = info.hasDefault;
12782            res.labelRes = info.labelRes;
12783            res.nonLocalizedLabel = info.nonLocalizedLabel;
12784            if (userNeedsBadging(userId)) {
12785                res.noResourceId = true;
12786            } else {
12787                res.icon = info.icon;
12788            }
12789            res.iconResourceId = info.icon;
12790            res.system = res.activityInfo.applicationInfo.isSystemApp();
12791            res.isInstantAppAvailable = userState.instantApp;
12792            return res;
12793        }
12794
12795        @Override
12796        protected void sortResults(List<ResolveInfo> results) {
12797            Collections.sort(results, mResolvePrioritySorter);
12798        }
12799
12800        @Override
12801        protected void dumpFilter(PrintWriter out, String prefix,
12802                PackageParser.ActivityIntentInfo filter) {
12803            out.print(prefix); out.print(
12804                    Integer.toHexString(System.identityHashCode(filter.activity)));
12805                    out.print(' ');
12806                    filter.activity.printComponentShortName(out);
12807                    out.print(" filter ");
12808                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12809        }
12810
12811        @Override
12812        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12813            return filter.activity;
12814        }
12815
12816        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12817            PackageParser.Activity activity = (PackageParser.Activity)label;
12818            out.print(prefix); out.print(
12819                    Integer.toHexString(System.identityHashCode(activity)));
12820                    out.print(' ');
12821                    activity.printComponentShortName(out);
12822            if (count > 1) {
12823                out.print(" ("); out.print(count); out.print(" filters)");
12824            }
12825            out.println();
12826        }
12827
12828        // Keys are String (activity class name), values are Activity.
12829        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12830                = new ArrayMap<ComponentName, PackageParser.Activity>();
12831        private int mFlags;
12832    }
12833
12834    private final class ServiceIntentResolver
12835            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12836        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12837                boolean defaultOnly, int userId) {
12838            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12839            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12840        }
12841
12842        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12843                int userId) {
12844            if (!sUserManager.exists(userId)) return null;
12845            mFlags = flags;
12846            return super.queryIntent(intent, resolvedType,
12847                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12848                    userId);
12849        }
12850
12851        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12852                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12853            if (!sUserManager.exists(userId)) return null;
12854            if (packageServices == null) {
12855                return null;
12856            }
12857            mFlags = flags;
12858            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12859            final int N = packageServices.size();
12860            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12861                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12862
12863            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12864            for (int i = 0; i < N; ++i) {
12865                intentFilters = packageServices.get(i).intents;
12866                if (intentFilters != null && intentFilters.size() > 0) {
12867                    PackageParser.ServiceIntentInfo[] array =
12868                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12869                    intentFilters.toArray(array);
12870                    listCut.add(array);
12871                }
12872            }
12873            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12874        }
12875
12876        public final void addService(PackageParser.Service s) {
12877            mServices.put(s.getComponentName(), s);
12878            if (DEBUG_SHOW_INFO) {
12879                Log.v(TAG, "  "
12880                        + (s.info.nonLocalizedLabel != null
12881                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12882                Log.v(TAG, "    Class=" + s.info.name);
12883            }
12884            final int NI = s.intents.size();
12885            int j;
12886            for (j=0; j<NI; j++) {
12887                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12888                if (DEBUG_SHOW_INFO) {
12889                    Log.v(TAG, "    IntentFilter:");
12890                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12891                }
12892                if (!intent.debugCheck()) {
12893                    Log.w(TAG, "==> For Service " + s.info.name);
12894                }
12895                addFilter(intent);
12896            }
12897        }
12898
12899        public final void removeService(PackageParser.Service s) {
12900            mServices.remove(s.getComponentName());
12901            if (DEBUG_SHOW_INFO) {
12902                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12903                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12904                Log.v(TAG, "    Class=" + s.info.name);
12905            }
12906            final int NI = s.intents.size();
12907            int j;
12908            for (j=0; j<NI; j++) {
12909                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12910                if (DEBUG_SHOW_INFO) {
12911                    Log.v(TAG, "    IntentFilter:");
12912                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12913                }
12914                removeFilter(intent);
12915            }
12916        }
12917
12918        @Override
12919        protected boolean allowFilterResult(
12920                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12921            ServiceInfo filterSi = filter.service.info;
12922            for (int i=dest.size()-1; i>=0; i--) {
12923                ServiceInfo destAi = dest.get(i).serviceInfo;
12924                if (destAi.name == filterSi.name
12925                        && destAi.packageName == filterSi.packageName) {
12926                    return false;
12927                }
12928            }
12929            return true;
12930        }
12931
12932        @Override
12933        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12934            return new PackageParser.ServiceIntentInfo[size];
12935        }
12936
12937        @Override
12938        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12939            if (!sUserManager.exists(userId)) return true;
12940            PackageParser.Package p = filter.service.owner;
12941            if (p != null) {
12942                PackageSetting ps = (PackageSetting)p.mExtras;
12943                if (ps != null) {
12944                    // System apps are never considered stopped for purposes of
12945                    // filtering, because there may be no way for the user to
12946                    // actually re-launch them.
12947                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12948                            && ps.getStopped(userId);
12949                }
12950            }
12951            return false;
12952        }
12953
12954        @Override
12955        protected boolean isPackageForFilter(String packageName,
12956                PackageParser.ServiceIntentInfo info) {
12957            return packageName.equals(info.service.owner.packageName);
12958        }
12959
12960        @Override
12961        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12962                int match, int userId) {
12963            if (!sUserManager.exists(userId)) return null;
12964            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12965            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12966                return null;
12967            }
12968            final PackageParser.Service service = info.service;
12969            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12970            if (ps == null) {
12971                return null;
12972            }
12973            final PackageUserState userState = ps.readUserState(userId);
12974            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12975                    userState, userId);
12976            if (si == null) {
12977                return null;
12978            }
12979            final boolean matchVisibleToInstantApp =
12980                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12981            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12982            // throw out filters that aren't visible to ephemeral apps
12983            if (matchVisibleToInstantApp
12984                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12985                return null;
12986            }
12987            // throw out ephemeral filters if we're not explicitly requesting them
12988            if (!isInstantApp && userState.instantApp) {
12989                return null;
12990            }
12991            // throw out instant app filters if updates are available; will trigger
12992            // instant app resolution
12993            if (userState.instantApp && ps.isUpdateAvailable()) {
12994                return null;
12995            }
12996            final ResolveInfo res = new ResolveInfo();
12997            res.serviceInfo = si;
12998            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12999                res.filter = filter;
13000            }
13001            res.priority = info.getPriority();
13002            res.preferredOrder = service.owner.mPreferredOrder;
13003            res.match = match;
13004            res.isDefault = info.hasDefault;
13005            res.labelRes = info.labelRes;
13006            res.nonLocalizedLabel = info.nonLocalizedLabel;
13007            res.icon = info.icon;
13008            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13009            return res;
13010        }
13011
13012        @Override
13013        protected void sortResults(List<ResolveInfo> results) {
13014            Collections.sort(results, mResolvePrioritySorter);
13015        }
13016
13017        @Override
13018        protected void dumpFilter(PrintWriter out, String prefix,
13019                PackageParser.ServiceIntentInfo filter) {
13020            out.print(prefix); out.print(
13021                    Integer.toHexString(System.identityHashCode(filter.service)));
13022                    out.print(' ');
13023                    filter.service.printComponentShortName(out);
13024                    out.print(" filter ");
13025                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13026                    if (filter.service.info.permission != null) {
13027                        out.print(" permission "); out.println(filter.service.info.permission);
13028                    } else {
13029                        out.println();
13030                    }
13031        }
13032
13033        @Override
13034        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13035            return filter.service;
13036        }
13037
13038        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13039            PackageParser.Service service = (PackageParser.Service)label;
13040            out.print(prefix); out.print(
13041                    Integer.toHexString(System.identityHashCode(service)));
13042                    out.print(' ');
13043                    service.printComponentShortName(out);
13044            if (count > 1) {
13045                out.print(" ("); out.print(count); out.print(" filters)");
13046            }
13047            out.println();
13048        }
13049
13050//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13051//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13052//            final List<ResolveInfo> retList = Lists.newArrayList();
13053//            while (i.hasNext()) {
13054//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13055//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13056//                    retList.add(resolveInfo);
13057//                }
13058//            }
13059//            return retList;
13060//        }
13061
13062        // Keys are String (activity class name), values are Activity.
13063        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13064                = new ArrayMap<ComponentName, PackageParser.Service>();
13065        private int mFlags;
13066    }
13067
13068    private final class ProviderIntentResolver
13069            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13070        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13071                boolean defaultOnly, int userId) {
13072            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13073            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13074        }
13075
13076        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13077                int userId) {
13078            if (!sUserManager.exists(userId))
13079                return null;
13080            mFlags = flags;
13081            return super.queryIntent(intent, resolvedType,
13082                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13083                    userId);
13084        }
13085
13086        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13087                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13088            if (!sUserManager.exists(userId))
13089                return null;
13090            if (packageProviders == null) {
13091                return null;
13092            }
13093            mFlags = flags;
13094            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13095            final int N = packageProviders.size();
13096            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13097                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13098
13099            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13100            for (int i = 0; i < N; ++i) {
13101                intentFilters = packageProviders.get(i).intents;
13102                if (intentFilters != null && intentFilters.size() > 0) {
13103                    PackageParser.ProviderIntentInfo[] array =
13104                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13105                    intentFilters.toArray(array);
13106                    listCut.add(array);
13107                }
13108            }
13109            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13110        }
13111
13112        public final void addProvider(PackageParser.Provider p) {
13113            if (mProviders.containsKey(p.getComponentName())) {
13114                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13115                return;
13116            }
13117
13118            mProviders.put(p.getComponentName(), p);
13119            if (DEBUG_SHOW_INFO) {
13120                Log.v(TAG, "  "
13121                        + (p.info.nonLocalizedLabel != null
13122                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13123                Log.v(TAG, "    Class=" + p.info.name);
13124            }
13125            final int NI = p.intents.size();
13126            int j;
13127            for (j = 0; j < NI; j++) {
13128                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13129                if (DEBUG_SHOW_INFO) {
13130                    Log.v(TAG, "    IntentFilter:");
13131                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13132                }
13133                if (!intent.debugCheck()) {
13134                    Log.w(TAG, "==> For Provider " + p.info.name);
13135                }
13136                addFilter(intent);
13137            }
13138        }
13139
13140        public final void removeProvider(PackageParser.Provider p) {
13141            mProviders.remove(p.getComponentName());
13142            if (DEBUG_SHOW_INFO) {
13143                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13144                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13145                Log.v(TAG, "    Class=" + p.info.name);
13146            }
13147            final int NI = p.intents.size();
13148            int j;
13149            for (j = 0; j < NI; j++) {
13150                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13151                if (DEBUG_SHOW_INFO) {
13152                    Log.v(TAG, "    IntentFilter:");
13153                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13154                }
13155                removeFilter(intent);
13156            }
13157        }
13158
13159        @Override
13160        protected boolean allowFilterResult(
13161                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13162            ProviderInfo filterPi = filter.provider.info;
13163            for (int i = dest.size() - 1; i >= 0; i--) {
13164                ProviderInfo destPi = dest.get(i).providerInfo;
13165                if (destPi.name == filterPi.name
13166                        && destPi.packageName == filterPi.packageName) {
13167                    return false;
13168                }
13169            }
13170            return true;
13171        }
13172
13173        @Override
13174        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13175            return new PackageParser.ProviderIntentInfo[size];
13176        }
13177
13178        @Override
13179        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13180            if (!sUserManager.exists(userId))
13181                return true;
13182            PackageParser.Package p = filter.provider.owner;
13183            if (p != null) {
13184                PackageSetting ps = (PackageSetting) p.mExtras;
13185                if (ps != null) {
13186                    // System apps are never considered stopped for purposes of
13187                    // filtering, because there may be no way for the user to
13188                    // actually re-launch them.
13189                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13190                            && ps.getStopped(userId);
13191                }
13192            }
13193            return false;
13194        }
13195
13196        @Override
13197        protected boolean isPackageForFilter(String packageName,
13198                PackageParser.ProviderIntentInfo info) {
13199            return packageName.equals(info.provider.owner.packageName);
13200        }
13201
13202        @Override
13203        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13204                int match, int userId) {
13205            if (!sUserManager.exists(userId))
13206                return null;
13207            final PackageParser.ProviderIntentInfo info = filter;
13208            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13209                return null;
13210            }
13211            final PackageParser.Provider provider = info.provider;
13212            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13213            if (ps == null) {
13214                return null;
13215            }
13216            final PackageUserState userState = ps.readUserState(userId);
13217            final boolean matchVisibleToInstantApp =
13218                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13219            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13220            // throw out filters that aren't visible to instant applications
13221            if (matchVisibleToInstantApp
13222                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13223                return null;
13224            }
13225            // throw out instant application filters if we're not explicitly requesting them
13226            if (!isInstantApp && userState.instantApp) {
13227                return null;
13228            }
13229            // throw out instant application filters if updates are available; will trigger
13230            // instant application resolution
13231            if (userState.instantApp && ps.isUpdateAvailable()) {
13232                return null;
13233            }
13234            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13235                    userState, userId);
13236            if (pi == null) {
13237                return null;
13238            }
13239            final ResolveInfo res = new ResolveInfo();
13240            res.providerInfo = pi;
13241            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13242                res.filter = filter;
13243            }
13244            res.priority = info.getPriority();
13245            res.preferredOrder = provider.owner.mPreferredOrder;
13246            res.match = match;
13247            res.isDefault = info.hasDefault;
13248            res.labelRes = info.labelRes;
13249            res.nonLocalizedLabel = info.nonLocalizedLabel;
13250            res.icon = info.icon;
13251            res.system = res.providerInfo.applicationInfo.isSystemApp();
13252            return res;
13253        }
13254
13255        @Override
13256        protected void sortResults(List<ResolveInfo> results) {
13257            Collections.sort(results, mResolvePrioritySorter);
13258        }
13259
13260        @Override
13261        protected void dumpFilter(PrintWriter out, String prefix,
13262                PackageParser.ProviderIntentInfo filter) {
13263            out.print(prefix);
13264            out.print(
13265                    Integer.toHexString(System.identityHashCode(filter.provider)));
13266            out.print(' ');
13267            filter.provider.printComponentShortName(out);
13268            out.print(" filter ");
13269            out.println(Integer.toHexString(System.identityHashCode(filter)));
13270        }
13271
13272        @Override
13273        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13274            return filter.provider;
13275        }
13276
13277        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13278            PackageParser.Provider provider = (PackageParser.Provider)label;
13279            out.print(prefix); out.print(
13280                    Integer.toHexString(System.identityHashCode(provider)));
13281                    out.print(' ');
13282                    provider.printComponentShortName(out);
13283            if (count > 1) {
13284                out.print(" ("); out.print(count); out.print(" filters)");
13285            }
13286            out.println();
13287        }
13288
13289        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13290                = new ArrayMap<ComponentName, PackageParser.Provider>();
13291        private int mFlags;
13292    }
13293
13294    static final class InstantAppIntentResolver
13295            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13296            AuxiliaryResolveInfo.AuxiliaryFilter> {
13297        /**
13298         * The result that has the highest defined order. Ordering applies on a
13299         * per-package basis. Mapping is from package name to Pair of order and
13300         * EphemeralResolveInfo.
13301         * <p>
13302         * NOTE: This is implemented as a field variable for convenience and efficiency.
13303         * By having a field variable, we're able to track filter ordering as soon as
13304         * a non-zero order is defined. Otherwise, multiple loops across the result set
13305         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13306         * this needs to be contained entirely within {@link #filterResults}.
13307         */
13308        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13309
13310        @Override
13311        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13312            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13313        }
13314
13315        @Override
13316        protected boolean isPackageForFilter(String packageName,
13317                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13318            return true;
13319        }
13320
13321        @Override
13322        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13323                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13324            if (!sUserManager.exists(userId)) {
13325                return null;
13326            }
13327            final String packageName = responseObj.resolveInfo.getPackageName();
13328            final Integer order = responseObj.getOrder();
13329            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13330                    mOrderResult.get(packageName);
13331            // ordering is enabled and this item's order isn't high enough
13332            if (lastOrderResult != null && lastOrderResult.first >= order) {
13333                return null;
13334            }
13335            final InstantAppResolveInfo res = responseObj.resolveInfo;
13336            if (order > 0) {
13337                // non-zero order, enable ordering
13338                mOrderResult.put(packageName, new Pair<>(order, res));
13339            }
13340            return responseObj;
13341        }
13342
13343        @Override
13344        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13345            // only do work if ordering is enabled [most of the time it won't be]
13346            if (mOrderResult.size() == 0) {
13347                return;
13348            }
13349            int resultSize = results.size();
13350            for (int i = 0; i < resultSize; i++) {
13351                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13352                final String packageName = info.getPackageName();
13353                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13354                if (savedInfo == null) {
13355                    // package doesn't having ordering
13356                    continue;
13357                }
13358                if (savedInfo.second == info) {
13359                    // circled back to the highest ordered item; remove from order list
13360                    mOrderResult.remove(packageName);
13361                    if (mOrderResult.size() == 0) {
13362                        // no more ordered items
13363                        break;
13364                    }
13365                    continue;
13366                }
13367                // item has a worse order, remove it from the result list
13368                results.remove(i);
13369                resultSize--;
13370                i--;
13371            }
13372        }
13373    }
13374
13375    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13376            new Comparator<ResolveInfo>() {
13377        public int compare(ResolveInfo r1, ResolveInfo r2) {
13378            int v1 = r1.priority;
13379            int v2 = r2.priority;
13380            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13381            if (v1 != v2) {
13382                return (v1 > v2) ? -1 : 1;
13383            }
13384            v1 = r1.preferredOrder;
13385            v2 = r2.preferredOrder;
13386            if (v1 != v2) {
13387                return (v1 > v2) ? -1 : 1;
13388            }
13389            if (r1.isDefault != r2.isDefault) {
13390                return r1.isDefault ? -1 : 1;
13391            }
13392            v1 = r1.match;
13393            v2 = r2.match;
13394            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13395            if (v1 != v2) {
13396                return (v1 > v2) ? -1 : 1;
13397            }
13398            if (r1.system != r2.system) {
13399                return r1.system ? -1 : 1;
13400            }
13401            if (r1.activityInfo != null) {
13402                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13403            }
13404            if (r1.serviceInfo != null) {
13405                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13406            }
13407            if (r1.providerInfo != null) {
13408                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13409            }
13410            return 0;
13411        }
13412    };
13413
13414    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13415            new Comparator<ProviderInfo>() {
13416        public int compare(ProviderInfo p1, ProviderInfo p2) {
13417            final int v1 = p1.initOrder;
13418            final int v2 = p2.initOrder;
13419            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13420        }
13421    };
13422
13423    @Override
13424    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13425            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13426            final int[] userIds, int[] instantUserIds) {
13427        mHandler.post(new Runnable() {
13428            @Override
13429            public void run() {
13430                try {
13431                    final IActivityManager am = ActivityManager.getService();
13432                    if (am == null) return;
13433                    final int[] resolvedUserIds;
13434                    if (userIds == null) {
13435                        resolvedUserIds = am.getRunningUserIds();
13436                    } else {
13437                        resolvedUserIds = userIds;
13438                    }
13439                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13440                            resolvedUserIds, false);
13441                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13442                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13443                                instantUserIds, true);
13444                    }
13445                } catch (RemoteException ex) {
13446                }
13447            }
13448        });
13449    }
13450
13451    @Override
13452    public void notifyPackageAdded(String packageName) {
13453        final PackageListObserver[] observers;
13454        synchronized (mPackages) {
13455            if (mPackageListObservers.size() == 0) {
13456                return;
13457            }
13458            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13459        }
13460        for (int i = observers.length - 1; i >= 0; --i) {
13461            observers[i].onPackageAdded(packageName);
13462        }
13463    }
13464
13465    @Override
13466    public void notifyPackageRemoved(String packageName) {
13467        final PackageListObserver[] observers;
13468        synchronized (mPackages) {
13469            if (mPackageListObservers.size() == 0) {
13470                return;
13471            }
13472            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13473        }
13474        for (int i = observers.length - 1; i >= 0; --i) {
13475            observers[i].onPackageRemoved(packageName);
13476        }
13477    }
13478
13479    /**
13480     * Sends a broadcast for the given action.
13481     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13482     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13483     * the system and applications allowed to see instant applications to receive package
13484     * lifecycle events for instant applications.
13485     */
13486    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13487            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13488            int[] userIds, boolean isInstantApp)
13489                    throws RemoteException {
13490        for (int id : userIds) {
13491            final Intent intent = new Intent(action,
13492                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13493            final String[] requiredPermissions =
13494                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13495            if (extras != null) {
13496                intent.putExtras(extras);
13497            }
13498            if (targetPkg != null) {
13499                intent.setPackage(targetPkg);
13500            }
13501            // Modify the UID when posting to other users
13502            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13503            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13504                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13505                intent.putExtra(Intent.EXTRA_UID, uid);
13506            }
13507            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13508            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13509            if (DEBUG_BROADCASTS) {
13510                RuntimeException here = new RuntimeException("here");
13511                here.fillInStackTrace();
13512                Slog.d(TAG, "Sending to user " + id + ": "
13513                        + intent.toShortString(false, true, false, false)
13514                        + " " + intent.getExtras(), here);
13515            }
13516            am.broadcastIntent(null, intent, null, finishedReceiver,
13517                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13518                    null, finishedReceiver != null, false, id);
13519        }
13520    }
13521
13522    /**
13523     * Check if the external storage media is available. This is true if there
13524     * is a mounted external storage medium or if the external storage is
13525     * emulated.
13526     */
13527    private boolean isExternalMediaAvailable() {
13528        return mMediaMounted || Environment.isExternalStorageEmulated();
13529    }
13530
13531    @Override
13532    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13533        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13534            return null;
13535        }
13536        if (!isExternalMediaAvailable()) {
13537                // If the external storage is no longer mounted at this point,
13538                // the caller may not have been able to delete all of this
13539                // packages files and can not delete any more.  Bail.
13540            return null;
13541        }
13542        synchronized (mPackages) {
13543            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13544            if (lastPackage != null) {
13545                pkgs.remove(lastPackage);
13546            }
13547            if (pkgs.size() > 0) {
13548                return pkgs.get(0);
13549            }
13550        }
13551        return null;
13552    }
13553
13554    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13555        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13556                userId, andCode ? 1 : 0, packageName);
13557        if (mSystemReady) {
13558            msg.sendToTarget();
13559        } else {
13560            if (mPostSystemReadyMessages == null) {
13561                mPostSystemReadyMessages = new ArrayList<>();
13562            }
13563            mPostSystemReadyMessages.add(msg);
13564        }
13565    }
13566
13567    void startCleaningPackages() {
13568        // reader
13569        if (!isExternalMediaAvailable()) {
13570            return;
13571        }
13572        synchronized (mPackages) {
13573            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13574                return;
13575            }
13576        }
13577        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13578        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13579        IActivityManager am = ActivityManager.getService();
13580        if (am != null) {
13581            int dcsUid = -1;
13582            synchronized (mPackages) {
13583                if (!mDefaultContainerWhitelisted) {
13584                    mDefaultContainerWhitelisted = true;
13585                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13586                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13587                }
13588            }
13589            try {
13590                if (dcsUid > 0) {
13591                    am.backgroundWhitelistUid(dcsUid);
13592                }
13593                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13594                        UserHandle.USER_SYSTEM);
13595            } catch (RemoteException e) {
13596            }
13597        }
13598    }
13599
13600    /**
13601     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13602     * it is acting on behalf on an enterprise or the user).
13603     *
13604     * Note that the ordering of the conditionals in this method is important. The checks we perform
13605     * are as follows, in this order:
13606     *
13607     * 1) If the install is being performed by a system app, we can trust the app to have set the
13608     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13609     *    what it is.
13610     * 2) If the install is being performed by a device or profile owner app, the install reason
13611     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13612     *    set the install reason correctly. If the app targets an older SDK version where install
13613     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13614     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13615     * 3) In all other cases, the install is being performed by a regular app that is neither part
13616     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13617     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13618     *    set to enterprise policy and if so, change it to unknown instead.
13619     */
13620    private int fixUpInstallReason(String installerPackageName, int installerUid,
13621            int installReason) {
13622        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13623                == PERMISSION_GRANTED) {
13624            // If the install is being performed by a system app, we trust that app to have set the
13625            // install reason correctly.
13626            return installReason;
13627        }
13628        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13629                UserHandle.getUserId(installerUid));
13630        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13631            // If the install is being performed by a device or profile owner, the install
13632            // reason should be enterprise policy.
13633            return PackageManager.INSTALL_REASON_POLICY;
13634        }
13635
13636
13637        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13638            // If the install is being performed by a regular app (i.e. neither system app nor
13639            // device or profile owner), we have no reason to believe that the app is acting on
13640            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13641            // change it to unknown instead.
13642            return PackageManager.INSTALL_REASON_UNKNOWN;
13643        }
13644
13645        // If the install is being performed by a regular app and the install reason was set to any
13646        // value but enterprise policy, leave the install reason unchanged.
13647        return installReason;
13648    }
13649
13650    /**
13651     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13652     * install commit.
13653     */
13654    void earlyBindToDefContainer() {
13655        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13656    }
13657
13658    void installStage(String packageName, File stagedDir,
13659            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13660            String installerPackageName, int installerUid, UserHandle user,
13661            PackageParser.SigningDetails signingDetails) {
13662        if (DEBUG_INSTANT) {
13663            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13664                Slog.d(TAG, "Ephemeral install of " + packageName);
13665            }
13666        }
13667        final VerificationInfo verificationInfo = new VerificationInfo(
13668                sessionParams.originatingUri, sessionParams.referrerUri,
13669                sessionParams.originatingUid, installerUid);
13670
13671        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13672
13673        final Message msg = mHandler.obtainMessage(INIT_COPY);
13674        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13675                sessionParams.installReason);
13676        final InstallParams params = new InstallParams(origin, null, observer,
13677                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13678                verificationInfo, user, sessionParams.abiOverride,
13679                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13680        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13681        msg.obj = params;
13682
13683        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13684                System.identityHashCode(msg.obj));
13685        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13686                System.identityHashCode(msg.obj));
13687
13688        mHandler.sendMessage(msg);
13689    }
13690
13691    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13692            int userId) {
13693        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13694        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13695        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13696        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13697        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13698                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13699
13700        // Send a session commit broadcast
13701        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13702        info.installReason = pkgSetting.getInstallReason(userId);
13703        info.appPackageName = packageName;
13704        sendSessionCommitBroadcast(info, userId);
13705    }
13706
13707    @Override
13708    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13709            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13710        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13711            return;
13712        }
13713        Bundle extras = new Bundle(1);
13714        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13715        final int uid = UserHandle.getUid(
13716                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13717        extras.putInt(Intent.EXTRA_UID, uid);
13718
13719        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13720                packageName, extras, 0, null, null, userIds, instantUserIds);
13721        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13722            mHandler.post(() -> {
13723                        for (int userId : userIds) {
13724                            sendBootCompletedBroadcastToSystemApp(
13725                                    packageName, includeStopped, userId);
13726                        }
13727                    }
13728            );
13729        }
13730    }
13731
13732    /**
13733     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13734     * automatically without needing an explicit launch.
13735     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13736     */
13737    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13738            int userId) {
13739        // If user is not running, the app didn't miss any broadcast
13740        if (!mUserManagerInternal.isUserRunning(userId)) {
13741            return;
13742        }
13743        final IActivityManager am = ActivityManager.getService();
13744        try {
13745            // Deliver LOCKED_BOOT_COMPLETED first
13746            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13747                    .setPackage(packageName);
13748            if (includeStopped) {
13749                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13750            }
13751            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13752            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13753                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13754
13755            // Deliver BOOT_COMPLETED only if user is unlocked
13756            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13757                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13758                if (includeStopped) {
13759                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13760                }
13761                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13762                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13763            }
13764        } catch (RemoteException e) {
13765            throw e.rethrowFromSystemServer();
13766        }
13767    }
13768
13769    @Override
13770    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13771            int userId) {
13772        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13773        PackageSetting pkgSetting;
13774        final int callingUid = Binder.getCallingUid();
13775        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13776                true /* requireFullPermission */, true /* checkShell */,
13777                "setApplicationHiddenSetting for user " + userId);
13778
13779        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13780            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13781            return false;
13782        }
13783
13784        long callingId = Binder.clearCallingIdentity();
13785        try {
13786            boolean sendAdded = false;
13787            boolean sendRemoved = false;
13788            // writer
13789            synchronized (mPackages) {
13790                pkgSetting = mSettings.mPackages.get(packageName);
13791                if (pkgSetting == null) {
13792                    return false;
13793                }
13794                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13795                    return false;
13796                }
13797                // Do not allow "android" is being disabled
13798                if ("android".equals(packageName)) {
13799                    Slog.w(TAG, "Cannot hide package: android");
13800                    return false;
13801                }
13802                // Cannot hide static shared libs as they are considered
13803                // a part of the using app (emulating static linking). Also
13804                // static libs are installed always on internal storage.
13805                PackageParser.Package pkg = mPackages.get(packageName);
13806                if (pkg != null && pkg.staticSharedLibName != null) {
13807                    Slog.w(TAG, "Cannot hide package: " + packageName
13808                            + " providing static shared library: "
13809                            + pkg.staticSharedLibName);
13810                    return false;
13811                }
13812                // Only allow protected packages to hide themselves.
13813                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13814                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13815                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13816                    return false;
13817                }
13818
13819                if (pkgSetting.getHidden(userId) != hidden) {
13820                    pkgSetting.setHidden(hidden, userId);
13821                    mSettings.writePackageRestrictionsLPr(userId);
13822                    if (hidden) {
13823                        sendRemoved = true;
13824                    } else {
13825                        sendAdded = true;
13826                    }
13827                }
13828            }
13829            if (sendAdded) {
13830                sendPackageAddedForUser(packageName, pkgSetting, userId);
13831                return true;
13832            }
13833            if (sendRemoved) {
13834                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13835                        "hiding pkg");
13836                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13837                return true;
13838            }
13839        } finally {
13840            Binder.restoreCallingIdentity(callingId);
13841        }
13842        return false;
13843    }
13844
13845    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13846            int userId) {
13847        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13848        info.removedPackage = packageName;
13849        info.installerPackageName = pkgSetting.installerPackageName;
13850        info.removedUsers = new int[] {userId};
13851        info.broadcastUsers = new int[] {userId};
13852        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13853        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13854    }
13855
13856    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13857            PersistableBundle launcherExtras) {
13858        if (pkgList.length > 0) {
13859            Bundle extras = new Bundle(1);
13860            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13861            if (launcherExtras != null) {
13862                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13863                        new Bundle(launcherExtras.deepCopy()));
13864            }
13865            sendPackageBroadcast(
13866                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13867                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13868                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13869                    new int[] {userId}, null);
13870        }
13871    }
13872
13873    /**
13874     * Returns true if application is not found or there was an error. Otherwise it returns
13875     * the hidden state of the package for the given user.
13876     */
13877    @Override
13878    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13880        final int callingUid = Binder.getCallingUid();
13881        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13882                true /* requireFullPermission */, false /* checkShell */,
13883                "getApplicationHidden for user " + userId);
13884        PackageSetting ps;
13885        long callingId = Binder.clearCallingIdentity();
13886        try {
13887            // writer
13888            synchronized (mPackages) {
13889                ps = mSettings.mPackages.get(packageName);
13890                if (ps == null) {
13891                    return true;
13892                }
13893                if (filterAppAccessLPr(ps, callingUid, userId)) {
13894                    return true;
13895                }
13896                return ps.getHidden(userId);
13897            }
13898        } finally {
13899            Binder.restoreCallingIdentity(callingId);
13900        }
13901    }
13902
13903    /**
13904     * @hide
13905     */
13906    @Override
13907    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13908            int installReason) {
13909        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13910                null);
13911        PackageSetting pkgSetting;
13912        final int callingUid = Binder.getCallingUid();
13913        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13914                true /* requireFullPermission */, true /* checkShell */,
13915                "installExistingPackage for user " + userId);
13916        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13917            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13918        }
13919
13920        long callingId = Binder.clearCallingIdentity();
13921        try {
13922            boolean installed = false;
13923            final boolean instantApp =
13924                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13925            final boolean fullApp =
13926                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13927
13928            // writer
13929            synchronized (mPackages) {
13930                pkgSetting = mSettings.mPackages.get(packageName);
13931                if (pkgSetting == null) {
13932                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13933                }
13934                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13935                    // only allow the existing package to be used if it's installed as a full
13936                    // application for at least one user
13937                    boolean installAllowed = false;
13938                    for (int checkUserId : sUserManager.getUserIds()) {
13939                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13940                        if (installAllowed) {
13941                            break;
13942                        }
13943                    }
13944                    if (!installAllowed) {
13945                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13946                    }
13947                }
13948                if (!pkgSetting.getInstalled(userId)) {
13949                    pkgSetting.setInstalled(true, userId);
13950                    pkgSetting.setHidden(false, userId);
13951                    pkgSetting.setInstallReason(installReason, userId);
13952                    mSettings.writePackageRestrictionsLPr(userId);
13953                    mSettings.writeKernelMappingLPr(pkgSetting);
13954                    installed = true;
13955                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13956                    // upgrade app from instant to full; we don't allow app downgrade
13957                    installed = true;
13958                }
13959                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13960            }
13961
13962            if (installed) {
13963                if (pkgSetting.pkg != null) {
13964                    synchronized (mInstallLock) {
13965                        // We don't need to freeze for a brand new install
13966                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13967                    }
13968                }
13969                sendPackageAddedForUser(packageName, pkgSetting, userId);
13970                synchronized (mPackages) {
13971                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13972                }
13973            }
13974        } finally {
13975            Binder.restoreCallingIdentity(callingId);
13976        }
13977
13978        return PackageManager.INSTALL_SUCCEEDED;
13979    }
13980
13981    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13982            boolean instantApp, boolean fullApp) {
13983        // no state specified; do nothing
13984        if (!instantApp && !fullApp) {
13985            return;
13986        }
13987        if (userId != UserHandle.USER_ALL) {
13988            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13989                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13990            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13991                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13992            }
13993        } else {
13994            for (int currentUserId : sUserManager.getUserIds()) {
13995                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13996                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13997                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13998                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13999                }
14000            }
14001        }
14002    }
14003
14004    boolean isUserRestricted(int userId, String restrictionKey) {
14005        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14006        if (restrictions.getBoolean(restrictionKey, false)) {
14007            Log.w(TAG, "User is restricted: " + restrictionKey);
14008            return true;
14009        }
14010        return false;
14011    }
14012
14013    @Override
14014    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14015            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14016            String callingPackage, int userId) {
14017        try {
14018            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14019        } catch (SecurityException e) {
14020            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14021                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14022                            + Manifest.permission.MANAGE_USERS);
14023        }
14024        final int callingUid = Binder.getCallingUid();
14025        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14026                true /* requireFullPermission */, true /* checkShell */,
14027                "setPackagesSuspended for user " + userId);
14028        if (callingUid != Process.ROOT_UID &&
14029                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
14030            throw new IllegalArgumentException("CallingPackage " + callingPackage + " does not"
14031                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14032        }
14033        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14034                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14035            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14036                    + userId + " has an active DO or PO");
14037        }
14038        if (ArrayUtils.isEmpty(packageNames)) {
14039            return packageNames;
14040        }
14041
14042        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14043        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14044        final long callingId = Binder.clearCallingIdentity();
14045        try {
14046            synchronized (mPackages) {
14047                for (int i = 0; i < packageNames.length; i++) {
14048                    final String packageName = packageNames[i];
14049                    if (callingPackage.equals(packageName)) {
14050                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14051                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14052                        unactionedPackages.add(packageName);
14053                        continue;
14054                    }
14055                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14056                    if (pkgSetting == null
14057                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14058                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14059                                + ". Skipping suspending/un-suspending.");
14060                        unactionedPackages.add(packageName);
14061                        continue;
14062                    }
14063                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14064                        unactionedPackages.add(packageName);
14065                        continue;
14066                    }
14067                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14068                            launcherExtras, userId);
14069                    changedPackagesList.add(packageName);
14070                }
14071            }
14072        } finally {
14073            Binder.restoreCallingIdentity(callingId);
14074        }
14075        if (!changedPackagesList.isEmpty()) {
14076            final String[] changedPackages = changedPackagesList.toArray(
14077                    new String[changedPackagesList.size()]);
14078            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14079            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14080            synchronized (mPackages) {
14081                scheduleWritePackageRestrictionsLocked(userId);
14082            }
14083        }
14084        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14085    }
14086
14087    @Override
14088    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14089        final int callingUid = Binder.getCallingUid();
14090        if (getPackageUid(packageName, 0, userId) != callingUid) {
14091            throw new SecurityException("Calling package " + packageName
14092                    + " does not belong to calling uid " + callingUid);
14093        }
14094        synchronized (mPackages) {
14095            final PackageSetting ps = mSettings.mPackages.get(packageName);
14096            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14097                throw new IllegalArgumentException("Unknown target package: " + packageName);
14098            }
14099            final PackageUserState packageUserState = ps.readUserState(userId);
14100            if (packageUserState.suspended) {
14101                return packageUserState.suspendedAppExtras;
14102            }
14103            return null;
14104        }
14105    }
14106
14107    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14108            PersistableBundle appExtras, int userId) {
14109        final String action;
14110        final Bundle intentExtras = new Bundle();
14111        if (suspended) {
14112            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14113            if (appExtras != null) {
14114                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14115                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14116            }
14117        } else {
14118            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14119        }
14120        mHandler.post(new Runnable() {
14121            @Override
14122            public void run() {
14123                try {
14124                    final IActivityManager am = ActivityManager.getService();
14125                    if (am == null) {
14126                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14127                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14128                        return;
14129                    }
14130                    final int[] targetUserIds = new int[] {userId};
14131                    for (String packageName : affectedPackages) {
14132                        doSendBroadcast(am, action, null, intentExtras,
14133                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14134                                targetUserIds, false);
14135                    }
14136                } catch (RemoteException ex) {
14137                    // Shouldn't happen as AMS is in the same process.
14138                }
14139            }
14140        });
14141    }
14142
14143    @Override
14144    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14145        final int callingUid = Binder.getCallingUid();
14146        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14147                true /* requireFullPermission */, false /* checkShell */,
14148                "isPackageSuspendedForUser for user " + userId);
14149        synchronized (mPackages) {
14150            final PackageSetting ps = mSettings.mPackages.get(packageName);
14151            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14152                throw new IllegalArgumentException("Unknown target package: " + packageName);
14153            }
14154            return ps.getSuspended(userId);
14155        }
14156    }
14157
14158    void onSuspendingPackageRemoved(String packageName, int removedForUser) {
14159        final int[] userIds = (removedForUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14160                : new int[] {removedForUser};
14161        for (int userId : userIds) {
14162            List<String> affectedPackages = new ArrayList<>();
14163            synchronized (mPackages) {
14164                for (PackageSetting ps : mSettings.mPackages.values()) {
14165                    final PackageUserState pus = ps.readUserState(userId);
14166                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14167                        ps.setSuspended(false, null, null, null, null, userId);
14168                        affectedPackages.add(ps.name);
14169                    }
14170                }
14171            }
14172            if (!affectedPackages.isEmpty()) {
14173                final String[] packageArray = affectedPackages.toArray(
14174                        new String[affectedPackages.size()]);
14175                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14176                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14177            }
14178        }
14179    }
14180
14181    @GuardedBy("mPackages")
14182    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14183        if (isPackageDeviceAdmin(packageName, userId)) {
14184            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14185                    + "\": has an active device admin");
14186            return false;
14187        }
14188
14189        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14190        if (packageName.equals(activeLauncherPackageName)) {
14191            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14192                    + "\": contains the active launcher");
14193            return false;
14194        }
14195
14196        if (packageName.equals(mRequiredInstallerPackage)) {
14197            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14198                    + "\": required for package installation");
14199            return false;
14200        }
14201
14202        if (packageName.equals(mRequiredUninstallerPackage)) {
14203            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14204                    + "\": required for package uninstallation");
14205            return false;
14206        }
14207
14208        if (packageName.equals(mRequiredVerifierPackage)) {
14209            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14210                    + "\": required for package verification");
14211            return false;
14212        }
14213
14214        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14215            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14216                    + "\": is the default dialer");
14217            return false;
14218        }
14219
14220        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14221            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14222                    + "\": protected package");
14223            return false;
14224        }
14225
14226        // Cannot suspend static shared libs as they are considered
14227        // a part of the using app (emulating static linking). Also
14228        // static libs are installed always on internal storage.
14229        PackageParser.Package pkg = mPackages.get(packageName);
14230        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14231            Slog.w(TAG, "Cannot suspend package: " + packageName
14232                    + " providing static shared library: "
14233                    + pkg.staticSharedLibName);
14234            return false;
14235        }
14236
14237        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14238            Slog.w(TAG, "Cannot suspend package: " + packageName);
14239            return false;
14240        }
14241
14242        return true;
14243    }
14244
14245    private String getActiveLauncherPackageName(int userId) {
14246        Intent intent = new Intent(Intent.ACTION_MAIN);
14247        intent.addCategory(Intent.CATEGORY_HOME);
14248        ResolveInfo resolveInfo = resolveIntent(
14249                intent,
14250                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14251                PackageManager.MATCH_DEFAULT_ONLY,
14252                userId);
14253
14254        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14255    }
14256
14257    private String getDefaultDialerPackageName(int userId) {
14258        synchronized (mPackages) {
14259            return mSettings.getDefaultDialerPackageNameLPw(userId);
14260        }
14261    }
14262
14263    @Override
14264    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14265        mContext.enforceCallingOrSelfPermission(
14266                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14267                "Only package verification agents can verify applications");
14268
14269        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14270        final PackageVerificationResponse response = new PackageVerificationResponse(
14271                verificationCode, Binder.getCallingUid());
14272        msg.arg1 = id;
14273        msg.obj = response;
14274        mHandler.sendMessage(msg);
14275    }
14276
14277    @Override
14278    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14279            long millisecondsToDelay) {
14280        mContext.enforceCallingOrSelfPermission(
14281                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14282                "Only package verification agents can extend verification timeouts");
14283
14284        final PackageVerificationState state = mPendingVerification.get(id);
14285        final PackageVerificationResponse response = new PackageVerificationResponse(
14286                verificationCodeAtTimeout, Binder.getCallingUid());
14287
14288        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14289            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14290        }
14291        if (millisecondsToDelay < 0) {
14292            millisecondsToDelay = 0;
14293        }
14294        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14295                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14296            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14297        }
14298
14299        if ((state != null) && !state.timeoutExtended()) {
14300            state.extendTimeout();
14301
14302            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14303            msg.arg1 = id;
14304            msg.obj = response;
14305            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14306        }
14307    }
14308
14309    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14310            int verificationCode, UserHandle user) {
14311        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14312        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14313        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14314        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14315        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14316
14317        mContext.sendBroadcastAsUser(intent, user,
14318                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14319    }
14320
14321    private ComponentName matchComponentForVerifier(String packageName,
14322            List<ResolveInfo> receivers) {
14323        ActivityInfo targetReceiver = null;
14324
14325        final int NR = receivers.size();
14326        for (int i = 0; i < NR; i++) {
14327            final ResolveInfo info = receivers.get(i);
14328            if (info.activityInfo == null) {
14329                continue;
14330            }
14331
14332            if (packageName.equals(info.activityInfo.packageName)) {
14333                targetReceiver = info.activityInfo;
14334                break;
14335            }
14336        }
14337
14338        if (targetReceiver == null) {
14339            return null;
14340        }
14341
14342        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14343    }
14344
14345    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14346            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14347        if (pkgInfo.verifiers.length == 0) {
14348            return null;
14349        }
14350
14351        final int N = pkgInfo.verifiers.length;
14352        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14353        for (int i = 0; i < N; i++) {
14354            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14355
14356            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14357                    receivers);
14358            if (comp == null) {
14359                continue;
14360            }
14361
14362            final int verifierUid = getUidForVerifier(verifierInfo);
14363            if (verifierUid == -1) {
14364                continue;
14365            }
14366
14367            if (DEBUG_VERIFY) {
14368                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14369                        + " with the correct signature");
14370            }
14371            sufficientVerifiers.add(comp);
14372            verificationState.addSufficientVerifier(verifierUid);
14373        }
14374
14375        return sufficientVerifiers;
14376    }
14377
14378    private int getUidForVerifier(VerifierInfo verifierInfo) {
14379        synchronized (mPackages) {
14380            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14381            if (pkg == null) {
14382                return -1;
14383            } else if (pkg.mSigningDetails.signatures.length != 1) {
14384                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14385                        + " has more than one signature; ignoring");
14386                return -1;
14387            }
14388
14389            /*
14390             * If the public key of the package's signature does not match
14391             * our expected public key, then this is a different package and
14392             * we should skip.
14393             */
14394
14395            final byte[] expectedPublicKey;
14396            try {
14397                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14398                final PublicKey publicKey = verifierSig.getPublicKey();
14399                expectedPublicKey = publicKey.getEncoded();
14400            } catch (CertificateException e) {
14401                return -1;
14402            }
14403
14404            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14405
14406            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14407                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14408                        + " does not have the expected public key; ignoring");
14409                return -1;
14410            }
14411
14412            return pkg.applicationInfo.uid;
14413        }
14414    }
14415
14416    @Override
14417    public void finishPackageInstall(int token, boolean didLaunch) {
14418        enforceSystemOrRoot("Only the system is allowed to finish installs");
14419
14420        if (DEBUG_INSTALL) {
14421            Slog.v(TAG, "BM finishing package install for " + token);
14422        }
14423        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14424
14425        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14426        mHandler.sendMessage(msg);
14427    }
14428
14429    /**
14430     * Get the verification agent timeout.  Used for both the APK verifier and the
14431     * intent filter verifier.
14432     *
14433     * @return verification timeout in milliseconds
14434     */
14435    private long getVerificationTimeout() {
14436        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14437                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14438                DEFAULT_VERIFICATION_TIMEOUT);
14439    }
14440
14441    /**
14442     * Get the default verification agent response code.
14443     *
14444     * @return default verification response code
14445     */
14446    private int getDefaultVerificationResponse(UserHandle user) {
14447        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14448            return PackageManager.VERIFICATION_REJECT;
14449        }
14450        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14451                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14452                DEFAULT_VERIFICATION_RESPONSE);
14453    }
14454
14455    /**
14456     * Check whether or not package verification has been enabled.
14457     *
14458     * @return true if verification should be performed
14459     */
14460    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14461        if (!DEFAULT_VERIFY_ENABLE) {
14462            return false;
14463        }
14464
14465        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14466
14467        // Check if installing from ADB
14468        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14469            // Do not run verification in a test harness environment
14470            if (ActivityManager.isRunningInTestHarness()) {
14471                return false;
14472            }
14473            if (ensureVerifyAppsEnabled) {
14474                return true;
14475            }
14476            // Check if the developer does not want package verification for ADB installs
14477            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14478                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14479                return false;
14480            }
14481        } else {
14482            // only when not installed from ADB, skip verification for instant apps when
14483            // the installer and verifier are the same.
14484            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14485                if (mInstantAppInstallerActivity != null
14486                        && mInstantAppInstallerActivity.packageName.equals(
14487                                mRequiredVerifierPackage)) {
14488                    try {
14489                        mContext.getSystemService(AppOpsManager.class)
14490                                .checkPackage(installerUid, mRequiredVerifierPackage);
14491                        if (DEBUG_VERIFY) {
14492                            Slog.i(TAG, "disable verification for instant app");
14493                        }
14494                        return false;
14495                    } catch (SecurityException ignore) { }
14496                }
14497            }
14498        }
14499
14500        if (ensureVerifyAppsEnabled) {
14501            return true;
14502        }
14503
14504        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14505                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14506    }
14507
14508    @Override
14509    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14510            throws RemoteException {
14511        mContext.enforceCallingOrSelfPermission(
14512                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14513                "Only intentfilter verification agents can verify applications");
14514
14515        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14516        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14517                Binder.getCallingUid(), verificationCode, failedDomains);
14518        msg.arg1 = id;
14519        msg.obj = response;
14520        mHandler.sendMessage(msg);
14521    }
14522
14523    @Override
14524    public int getIntentVerificationStatus(String packageName, int userId) {
14525        final int callingUid = Binder.getCallingUid();
14526        if (UserHandle.getUserId(callingUid) != userId) {
14527            mContext.enforceCallingOrSelfPermission(
14528                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14529                    "getIntentVerificationStatus" + userId);
14530        }
14531        if (getInstantAppPackageName(callingUid) != null) {
14532            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14533        }
14534        synchronized (mPackages) {
14535            final PackageSetting ps = mSettings.mPackages.get(packageName);
14536            if (ps == null
14537                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14538                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14539            }
14540            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14541        }
14542    }
14543
14544    @Override
14545    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14546        mContext.enforceCallingOrSelfPermission(
14547                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14548
14549        boolean result = false;
14550        synchronized (mPackages) {
14551            final PackageSetting ps = mSettings.mPackages.get(packageName);
14552            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14553                return false;
14554            }
14555            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14556        }
14557        if (result) {
14558            scheduleWritePackageRestrictionsLocked(userId);
14559        }
14560        return result;
14561    }
14562
14563    @Override
14564    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14565            String packageName) {
14566        final int callingUid = Binder.getCallingUid();
14567        if (getInstantAppPackageName(callingUid) != null) {
14568            return ParceledListSlice.emptyList();
14569        }
14570        synchronized (mPackages) {
14571            final PackageSetting ps = mSettings.mPackages.get(packageName);
14572            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14573                return ParceledListSlice.emptyList();
14574            }
14575            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14576        }
14577    }
14578
14579    @Override
14580    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14581        if (TextUtils.isEmpty(packageName)) {
14582            return ParceledListSlice.emptyList();
14583        }
14584        final int callingUid = Binder.getCallingUid();
14585        final int callingUserId = UserHandle.getUserId(callingUid);
14586        synchronized (mPackages) {
14587            PackageParser.Package pkg = mPackages.get(packageName);
14588            if (pkg == null || pkg.activities == null) {
14589                return ParceledListSlice.emptyList();
14590            }
14591            if (pkg.mExtras == null) {
14592                return ParceledListSlice.emptyList();
14593            }
14594            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14595            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14596                return ParceledListSlice.emptyList();
14597            }
14598            final int count = pkg.activities.size();
14599            ArrayList<IntentFilter> result = new ArrayList<>();
14600            for (int n=0; n<count; n++) {
14601                PackageParser.Activity activity = pkg.activities.get(n);
14602                if (activity.intents != null && activity.intents.size() > 0) {
14603                    result.addAll(activity.intents);
14604                }
14605            }
14606            return new ParceledListSlice<>(result);
14607        }
14608    }
14609
14610    @Override
14611    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14612        mContext.enforceCallingOrSelfPermission(
14613                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14614        if (UserHandle.getCallingUserId() != userId) {
14615            mContext.enforceCallingOrSelfPermission(
14616                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14617        }
14618
14619        synchronized (mPackages) {
14620            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14621            if (packageName != null) {
14622                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14623                        packageName, userId);
14624            }
14625            return result;
14626        }
14627    }
14628
14629    @Override
14630    public String getDefaultBrowserPackageName(int userId) {
14631        if (UserHandle.getCallingUserId() != userId) {
14632            mContext.enforceCallingOrSelfPermission(
14633                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14634        }
14635        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14636            return null;
14637        }
14638        synchronized (mPackages) {
14639            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14640        }
14641    }
14642
14643    /**
14644     * Get the "allow unknown sources" setting.
14645     *
14646     * @return the current "allow unknown sources" setting
14647     */
14648    private int getUnknownSourcesSettings() {
14649        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14650                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14651                -1);
14652    }
14653
14654    @Override
14655    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14656        final int callingUid = Binder.getCallingUid();
14657        if (getInstantAppPackageName(callingUid) != null) {
14658            return;
14659        }
14660        // writer
14661        synchronized (mPackages) {
14662            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14663            if (targetPackageSetting == null
14664                    || filterAppAccessLPr(
14665                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14666                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14667            }
14668
14669            PackageSetting installerPackageSetting;
14670            if (installerPackageName != null) {
14671                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14672                if (installerPackageSetting == null) {
14673                    throw new IllegalArgumentException("Unknown installer package: "
14674                            + installerPackageName);
14675                }
14676            } else {
14677                installerPackageSetting = null;
14678            }
14679
14680            Signature[] callerSignature;
14681            Object obj = mSettings.getUserIdLPr(callingUid);
14682            if (obj != null) {
14683                if (obj instanceof SharedUserSetting) {
14684                    callerSignature =
14685                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14686                } else if (obj instanceof PackageSetting) {
14687                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14688                } else {
14689                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14690                }
14691            } else {
14692                throw new SecurityException("Unknown calling UID: " + callingUid);
14693            }
14694
14695            // Verify: can't set installerPackageName to a package that is
14696            // not signed with the same cert as the caller.
14697            if (installerPackageSetting != null) {
14698                if (compareSignatures(callerSignature,
14699                        installerPackageSetting.signatures.mSigningDetails.signatures)
14700                        != PackageManager.SIGNATURE_MATCH) {
14701                    throw new SecurityException(
14702                            "Caller does not have same cert as new installer package "
14703                            + installerPackageName);
14704                }
14705            }
14706
14707            // Verify: if target already has an installer package, it must
14708            // be signed with the same cert as the caller.
14709            if (targetPackageSetting.installerPackageName != null) {
14710                PackageSetting setting = mSettings.mPackages.get(
14711                        targetPackageSetting.installerPackageName);
14712                // If the currently set package isn't valid, then it's always
14713                // okay to change it.
14714                if (setting != null) {
14715                    if (compareSignatures(callerSignature,
14716                            setting.signatures.mSigningDetails.signatures)
14717                            != PackageManager.SIGNATURE_MATCH) {
14718                        throw new SecurityException(
14719                                "Caller does not have same cert as old installer package "
14720                                + targetPackageSetting.installerPackageName);
14721                    }
14722                }
14723            }
14724
14725            // Okay!
14726            targetPackageSetting.installerPackageName = installerPackageName;
14727            if (installerPackageName != null) {
14728                mSettings.mInstallerPackages.add(installerPackageName);
14729            }
14730            scheduleWriteSettingsLocked();
14731        }
14732    }
14733
14734    @Override
14735    public void setApplicationCategoryHint(String packageName, int categoryHint,
14736            String callerPackageName) {
14737        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14738            throw new SecurityException("Instant applications don't have access to this method");
14739        }
14740        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14741                callerPackageName);
14742        synchronized (mPackages) {
14743            PackageSetting ps = mSettings.mPackages.get(packageName);
14744            if (ps == null) {
14745                throw new IllegalArgumentException("Unknown target package " + packageName);
14746            }
14747            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14748                throw new IllegalArgumentException("Unknown target package " + packageName);
14749            }
14750            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14751                throw new IllegalArgumentException("Calling package " + callerPackageName
14752                        + " is not installer for " + packageName);
14753            }
14754
14755            if (ps.categoryHint != categoryHint) {
14756                ps.categoryHint = categoryHint;
14757                scheduleWriteSettingsLocked();
14758            }
14759        }
14760    }
14761
14762    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14763        // Queue up an async operation since the package installation may take a little while.
14764        mHandler.post(new Runnable() {
14765            public void run() {
14766                mHandler.removeCallbacks(this);
14767                 // Result object to be returned
14768                PackageInstalledInfo res = new PackageInstalledInfo();
14769                res.setReturnCode(currentStatus);
14770                res.uid = -1;
14771                res.pkg = null;
14772                res.removedInfo = null;
14773                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14774                    args.doPreInstall(res.returnCode);
14775                    synchronized (mInstallLock) {
14776                        installPackageTracedLI(args, res);
14777                    }
14778                    args.doPostInstall(res.returnCode, res.uid);
14779                }
14780
14781                // A restore should be performed at this point if (a) the install
14782                // succeeded, (b) the operation is not an update, and (c) the new
14783                // package has not opted out of backup participation.
14784                final boolean update = res.removedInfo != null
14785                        && res.removedInfo.removedPackage != null;
14786                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14787                boolean doRestore = !update
14788                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14789
14790                // Set up the post-install work request bookkeeping.  This will be used
14791                // and cleaned up by the post-install event handling regardless of whether
14792                // there's a restore pass performed.  Token values are >= 1.
14793                int token;
14794                if (mNextInstallToken < 0) mNextInstallToken = 1;
14795                token = mNextInstallToken++;
14796
14797                PostInstallData data = new PostInstallData(args, res);
14798                mRunningInstalls.put(token, data);
14799                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14800
14801                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14802                    // Pass responsibility to the Backup Manager.  It will perform a
14803                    // restore if appropriate, then pass responsibility back to the
14804                    // Package Manager to run the post-install observer callbacks
14805                    // and broadcasts.
14806                    IBackupManager bm = IBackupManager.Stub.asInterface(
14807                            ServiceManager.getService(Context.BACKUP_SERVICE));
14808                    if (bm != null) {
14809                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14810                                + " to BM for possible restore");
14811                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14812                        try {
14813                            // TODO: http://b/22388012
14814                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14815                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14816                            } else {
14817                                doRestore = false;
14818                            }
14819                        } catch (RemoteException e) {
14820                            // can't happen; the backup manager is local
14821                        } catch (Exception e) {
14822                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14823                            doRestore = false;
14824                        }
14825                    } else {
14826                        Slog.e(TAG, "Backup Manager not found!");
14827                        doRestore = false;
14828                    }
14829                }
14830
14831                if (!doRestore) {
14832                    // No restore possible, or the Backup Manager was mysteriously not
14833                    // available -- just fire the post-install work request directly.
14834                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14835
14836                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14837
14838                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14839                    mHandler.sendMessage(msg);
14840                }
14841            }
14842        });
14843    }
14844
14845    /**
14846     * Callback from PackageSettings whenever an app is first transitioned out of the
14847     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14848     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14849     * here whether the app is the target of an ongoing install, and only send the
14850     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14851     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14852     * handling.
14853     */
14854    void notifyFirstLaunch(final String packageName, final String installerPackage,
14855            final int userId) {
14856        // Serialize this with the rest of the install-process message chain.  In the
14857        // restore-at-install case, this Runnable will necessarily run before the
14858        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14859        // are coherent.  In the non-restore case, the app has already completed install
14860        // and been launched through some other means, so it is not in a problematic
14861        // state for observers to see the FIRST_LAUNCH signal.
14862        mHandler.post(new Runnable() {
14863            @Override
14864            public void run() {
14865                for (int i = 0; i < mRunningInstalls.size(); i++) {
14866                    final PostInstallData data = mRunningInstalls.valueAt(i);
14867                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14868                        continue;
14869                    }
14870                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14871                        // right package; but is it for the right user?
14872                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14873                            if (userId == data.res.newUsers[uIndex]) {
14874                                if (DEBUG_BACKUP) {
14875                                    Slog.i(TAG, "Package " + packageName
14876                                            + " being restored so deferring FIRST_LAUNCH");
14877                                }
14878                                return;
14879                            }
14880                        }
14881                    }
14882                }
14883                // didn't find it, so not being restored
14884                if (DEBUG_BACKUP) {
14885                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14886                }
14887                final boolean isInstantApp = isInstantApp(packageName, userId);
14888                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14889                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14890                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14891            }
14892        });
14893    }
14894
14895    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14896            int[] userIds, int[] instantUserIds) {
14897        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14898                installerPkg, null, userIds, instantUserIds);
14899    }
14900
14901    private abstract class HandlerParams {
14902        private static final int MAX_RETRIES = 4;
14903
14904        /**
14905         * Number of times startCopy() has been attempted and had a non-fatal
14906         * error.
14907         */
14908        private int mRetries = 0;
14909
14910        /** User handle for the user requesting the information or installation. */
14911        private final UserHandle mUser;
14912        String traceMethod;
14913        int traceCookie;
14914
14915        HandlerParams(UserHandle user) {
14916            mUser = user;
14917        }
14918
14919        UserHandle getUser() {
14920            return mUser;
14921        }
14922
14923        HandlerParams setTraceMethod(String traceMethod) {
14924            this.traceMethod = traceMethod;
14925            return this;
14926        }
14927
14928        HandlerParams setTraceCookie(int traceCookie) {
14929            this.traceCookie = traceCookie;
14930            return this;
14931        }
14932
14933        final boolean startCopy() {
14934            boolean res;
14935            try {
14936                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14937
14938                if (++mRetries > MAX_RETRIES) {
14939                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14940                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14941                    handleServiceError();
14942                    return false;
14943                } else {
14944                    handleStartCopy();
14945                    res = true;
14946                }
14947            } catch (RemoteException e) {
14948                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14949                mHandler.sendEmptyMessage(MCS_RECONNECT);
14950                res = false;
14951            }
14952            handleReturnCode();
14953            return res;
14954        }
14955
14956        final void serviceError() {
14957            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14958            handleServiceError();
14959            handleReturnCode();
14960        }
14961
14962        abstract void handleStartCopy() throws RemoteException;
14963        abstract void handleServiceError();
14964        abstract void handleReturnCode();
14965    }
14966
14967    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14968        for (File path : paths) {
14969            try {
14970                mcs.clearDirectory(path.getAbsolutePath());
14971            } catch (RemoteException e) {
14972            }
14973        }
14974    }
14975
14976    static class OriginInfo {
14977        /**
14978         * Location where install is coming from, before it has been
14979         * copied/renamed into place. This could be a single monolithic APK
14980         * file, or a cluster directory. This location may be untrusted.
14981         */
14982        final File file;
14983
14984        /**
14985         * Flag indicating that {@link #file} or {@link #cid} has already been
14986         * staged, meaning downstream users don't need to defensively copy the
14987         * contents.
14988         */
14989        final boolean staged;
14990
14991        /**
14992         * Flag indicating that {@link #file} or {@link #cid} is an already
14993         * installed app that is being moved.
14994         */
14995        final boolean existing;
14996
14997        final String resolvedPath;
14998        final File resolvedFile;
14999
15000        static OriginInfo fromNothing() {
15001            return new OriginInfo(null, false, false);
15002        }
15003
15004        static OriginInfo fromUntrustedFile(File file) {
15005            return new OriginInfo(file, false, false);
15006        }
15007
15008        static OriginInfo fromExistingFile(File file) {
15009            return new OriginInfo(file, false, true);
15010        }
15011
15012        static OriginInfo fromStagedFile(File file) {
15013            return new OriginInfo(file, true, false);
15014        }
15015
15016        private OriginInfo(File file, boolean staged, boolean existing) {
15017            this.file = file;
15018            this.staged = staged;
15019            this.existing = existing;
15020
15021            if (file != null) {
15022                resolvedPath = file.getAbsolutePath();
15023                resolvedFile = file;
15024            } else {
15025                resolvedPath = null;
15026                resolvedFile = null;
15027            }
15028        }
15029    }
15030
15031    static class MoveInfo {
15032        final int moveId;
15033        final String fromUuid;
15034        final String toUuid;
15035        final String packageName;
15036        final String dataAppName;
15037        final int appId;
15038        final String seinfo;
15039        final int targetSdkVersion;
15040
15041        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15042                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15043            this.moveId = moveId;
15044            this.fromUuid = fromUuid;
15045            this.toUuid = toUuid;
15046            this.packageName = packageName;
15047            this.dataAppName = dataAppName;
15048            this.appId = appId;
15049            this.seinfo = seinfo;
15050            this.targetSdkVersion = targetSdkVersion;
15051        }
15052    }
15053
15054    static class VerificationInfo {
15055        /** A constant used to indicate that a uid value is not present. */
15056        public static final int NO_UID = -1;
15057
15058        /** URI referencing where the package was downloaded from. */
15059        final Uri originatingUri;
15060
15061        /** HTTP referrer URI associated with the originatingURI. */
15062        final Uri referrer;
15063
15064        /** UID of the application that the install request originated from. */
15065        final int originatingUid;
15066
15067        /** UID of application requesting the install */
15068        final int installerUid;
15069
15070        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15071            this.originatingUri = originatingUri;
15072            this.referrer = referrer;
15073            this.originatingUid = originatingUid;
15074            this.installerUid = installerUid;
15075        }
15076    }
15077
15078    class InstallParams extends HandlerParams {
15079        final OriginInfo origin;
15080        final MoveInfo move;
15081        final IPackageInstallObserver2 observer;
15082        int installFlags;
15083        final String installerPackageName;
15084        final String volumeUuid;
15085        private InstallArgs mArgs;
15086        private int mRet;
15087        final String packageAbiOverride;
15088        final String[] grantedRuntimePermissions;
15089        final VerificationInfo verificationInfo;
15090        final PackageParser.SigningDetails signingDetails;
15091        final int installReason;
15092
15093        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15094                int installFlags, String installerPackageName, String volumeUuid,
15095                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15096                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15097            super(user);
15098            this.origin = origin;
15099            this.move = move;
15100            this.observer = observer;
15101            this.installFlags = installFlags;
15102            this.installerPackageName = installerPackageName;
15103            this.volumeUuid = volumeUuid;
15104            this.verificationInfo = verificationInfo;
15105            this.packageAbiOverride = packageAbiOverride;
15106            this.grantedRuntimePermissions = grantedPermissions;
15107            this.signingDetails = signingDetails;
15108            this.installReason = installReason;
15109        }
15110
15111        @Override
15112        public String toString() {
15113            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15114                    + " file=" + origin.file + "}";
15115        }
15116
15117        private int installLocationPolicy(PackageInfoLite pkgLite) {
15118            String packageName = pkgLite.packageName;
15119            int installLocation = pkgLite.installLocation;
15120            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15121            // reader
15122            synchronized (mPackages) {
15123                // Currently installed package which the new package is attempting to replace or
15124                // null if no such package is installed.
15125                PackageParser.Package installedPkg = mPackages.get(packageName);
15126                // Package which currently owns the data which the new package will own if installed.
15127                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15128                // will be null whereas dataOwnerPkg will contain information about the package
15129                // which was uninstalled while keeping its data.
15130                PackageParser.Package dataOwnerPkg = installedPkg;
15131                if (dataOwnerPkg  == null) {
15132                    PackageSetting ps = mSettings.mPackages.get(packageName);
15133                    if (ps != null) {
15134                        dataOwnerPkg = ps.pkg;
15135                    }
15136                }
15137
15138                if (dataOwnerPkg != null) {
15139                    // If installed, the package will get access to data left on the device by its
15140                    // predecessor. As a security measure, this is permited only if this is not a
15141                    // version downgrade or if the predecessor package is marked as debuggable and
15142                    // a downgrade is explicitly requested.
15143                    //
15144                    // On debuggable platform builds, downgrades are permitted even for
15145                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15146                    // not offer security guarantees and thus it's OK to disable some security
15147                    // mechanisms to make debugging/testing easier on those builds. However, even on
15148                    // debuggable builds downgrades of packages are permitted only if requested via
15149                    // installFlags. This is because we aim to keep the behavior of debuggable
15150                    // platform builds as close as possible to the behavior of non-debuggable
15151                    // platform builds.
15152                    final boolean downgradeRequested =
15153                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15154                    final boolean packageDebuggable =
15155                                (dataOwnerPkg.applicationInfo.flags
15156                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15157                    final boolean downgradePermitted =
15158                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15159                    if (!downgradePermitted) {
15160                        try {
15161                            checkDowngrade(dataOwnerPkg, pkgLite);
15162                        } catch (PackageManagerException e) {
15163                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15164                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15165                        }
15166                    }
15167                }
15168
15169                if (installedPkg != null) {
15170                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15171                        // Check for updated system application.
15172                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15173                            if (onSd) {
15174                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15175                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15176                            }
15177                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15178                        } else {
15179                            if (onSd) {
15180                                // Install flag overrides everything.
15181                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15182                            }
15183                            // If current upgrade specifies particular preference
15184                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15185                                // Application explicitly specified internal.
15186                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15187                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15188                                // App explictly prefers external. Let policy decide
15189                            } else {
15190                                // Prefer previous location
15191                                if (isExternal(installedPkg)) {
15192                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15193                                }
15194                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15195                            }
15196                        }
15197                    } else {
15198                        // Invalid install. Return error code
15199                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15200                    }
15201                }
15202            }
15203            // All the special cases have been taken care of.
15204            // Return result based on recommended install location.
15205            if (onSd) {
15206                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15207            }
15208            return pkgLite.recommendedInstallLocation;
15209        }
15210
15211        /*
15212         * Invoke remote method to get package information and install
15213         * location values. Override install location based on default
15214         * policy if needed and then create install arguments based
15215         * on the install location.
15216         */
15217        public void handleStartCopy() throws RemoteException {
15218            int ret = PackageManager.INSTALL_SUCCEEDED;
15219
15220            // If we're already staged, we've firmly committed to an install location
15221            if (origin.staged) {
15222                if (origin.file != null) {
15223                    installFlags |= PackageManager.INSTALL_INTERNAL;
15224                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15225                } else {
15226                    throw new IllegalStateException("Invalid stage location");
15227                }
15228            }
15229
15230            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15231            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15232            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15233            PackageInfoLite pkgLite = null;
15234
15235            if (onInt && onSd) {
15236                // Check if both bits are set.
15237                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15238                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15239            } else if (onSd && ephemeral) {
15240                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15241                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15242            } else {
15243                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15244                        packageAbiOverride);
15245
15246                if (DEBUG_INSTANT && ephemeral) {
15247                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15248                }
15249
15250                /*
15251                 * If we have too little free space, try to free cache
15252                 * before giving up.
15253                 */
15254                if (!origin.staged && pkgLite.recommendedInstallLocation
15255                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15256                    // TODO: focus freeing disk space on the target device
15257                    final StorageManager storage = StorageManager.from(mContext);
15258                    final long lowThreshold = storage.getStorageLowBytes(
15259                            Environment.getDataDirectory());
15260
15261                    final long sizeBytes = mContainerService.calculateInstalledSize(
15262                            origin.resolvedPath, packageAbiOverride);
15263
15264                    try {
15265                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15266                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15267                                installFlags, packageAbiOverride);
15268                    } catch (InstallerException e) {
15269                        Slog.w(TAG, "Failed to free cache", e);
15270                    }
15271
15272                    /*
15273                     * The cache free must have deleted the file we
15274                     * downloaded to install.
15275                     *
15276                     * TODO: fix the "freeCache" call to not delete
15277                     *       the file we care about.
15278                     */
15279                    if (pkgLite.recommendedInstallLocation
15280                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15281                        pkgLite.recommendedInstallLocation
15282                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15283                    }
15284                }
15285            }
15286
15287            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15288                int loc = pkgLite.recommendedInstallLocation;
15289                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15290                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15291                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15292                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15293                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15294                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15295                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15296                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15297                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15298                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15299                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15300                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15301                } else {
15302                    // Override with defaults if needed.
15303                    loc = installLocationPolicy(pkgLite);
15304                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15305                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15306                    } else if (!onSd && !onInt) {
15307                        // Override install location with flags
15308                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15309                            // Set the flag to install on external media.
15310                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15311                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15312                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15313                            if (DEBUG_INSTANT) {
15314                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15315                            }
15316                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15317                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15318                                    |PackageManager.INSTALL_INTERNAL);
15319                        } else {
15320                            // Make sure the flag for installing on external
15321                            // media is unset
15322                            installFlags |= PackageManager.INSTALL_INTERNAL;
15323                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15324                        }
15325                    }
15326                }
15327            }
15328
15329            final InstallArgs args = createInstallArgs(this);
15330            mArgs = args;
15331
15332            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15333                // TODO: http://b/22976637
15334                // Apps installed for "all" users use the device owner to verify the app
15335                UserHandle verifierUser = getUser();
15336                if (verifierUser == UserHandle.ALL) {
15337                    verifierUser = UserHandle.SYSTEM;
15338                }
15339
15340                /*
15341                 * Determine if we have any installed package verifiers. If we
15342                 * do, then we'll defer to them to verify the packages.
15343                 */
15344                final int requiredUid = mRequiredVerifierPackage == null ? -1
15345                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15346                                verifierUser.getIdentifier());
15347                final int installerUid =
15348                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15349                if (!origin.existing && requiredUid != -1
15350                        && isVerificationEnabled(
15351                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15352                    final Intent verification = new Intent(
15353                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15354                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15355                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15356                            PACKAGE_MIME_TYPE);
15357                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15358
15359                    // Query all live verifiers based on current user state
15360                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15361                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15362                            false /*allowDynamicSplits*/);
15363
15364                    if (DEBUG_VERIFY) {
15365                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15366                                + verification.toString() + " with " + pkgLite.verifiers.length
15367                                + " optional verifiers");
15368                    }
15369
15370                    final int verificationId = mPendingVerificationToken++;
15371
15372                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15373
15374                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15375                            installerPackageName);
15376
15377                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15378                            installFlags);
15379
15380                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15381                            pkgLite.packageName);
15382
15383                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15384                            pkgLite.versionCode);
15385
15386                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15387                            pkgLite.getLongVersionCode());
15388
15389                    if (verificationInfo != null) {
15390                        if (verificationInfo.originatingUri != null) {
15391                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15392                                    verificationInfo.originatingUri);
15393                        }
15394                        if (verificationInfo.referrer != null) {
15395                            verification.putExtra(Intent.EXTRA_REFERRER,
15396                                    verificationInfo.referrer);
15397                        }
15398                        if (verificationInfo.originatingUid >= 0) {
15399                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15400                                    verificationInfo.originatingUid);
15401                        }
15402                        if (verificationInfo.installerUid >= 0) {
15403                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15404                                    verificationInfo.installerUid);
15405                        }
15406                    }
15407
15408                    final PackageVerificationState verificationState = new PackageVerificationState(
15409                            requiredUid, args);
15410
15411                    mPendingVerification.append(verificationId, verificationState);
15412
15413                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15414                            receivers, verificationState);
15415
15416                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15417                    final long idleDuration = getVerificationTimeout();
15418
15419                    /*
15420                     * If any sufficient verifiers were listed in the package
15421                     * manifest, attempt to ask them.
15422                     */
15423                    if (sufficientVerifiers != null) {
15424                        final int N = sufficientVerifiers.size();
15425                        if (N == 0) {
15426                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15427                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15428                        } else {
15429                            for (int i = 0; i < N; i++) {
15430                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15431                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15432                                        verifierComponent.getPackageName(), idleDuration,
15433                                        verifierUser.getIdentifier(), false, "package verifier");
15434
15435                                final Intent sufficientIntent = new Intent(verification);
15436                                sufficientIntent.setComponent(verifierComponent);
15437                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15438                            }
15439                        }
15440                    }
15441
15442                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15443                            mRequiredVerifierPackage, receivers);
15444                    if (ret == PackageManager.INSTALL_SUCCEEDED
15445                            && mRequiredVerifierPackage != null) {
15446                        Trace.asyncTraceBegin(
15447                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15448                        /*
15449                         * Send the intent to the required verification agent,
15450                         * but only start the verification timeout after the
15451                         * target BroadcastReceivers have run.
15452                         */
15453                        verification.setComponent(requiredVerifierComponent);
15454                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15455                                mRequiredVerifierPackage, idleDuration,
15456                                verifierUser.getIdentifier(), false, "package verifier");
15457                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15458                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15459                                new BroadcastReceiver() {
15460                                    @Override
15461                                    public void onReceive(Context context, Intent intent) {
15462                                        final Message msg = mHandler
15463                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15464                                        msg.arg1 = verificationId;
15465                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15466                                    }
15467                                }, null, 0, null, null);
15468
15469                        /*
15470                         * We don't want the copy to proceed until verification
15471                         * succeeds, so null out this field.
15472                         */
15473                        mArgs = null;
15474                    }
15475                } else {
15476                    /*
15477                     * No package verification is enabled, so immediately start
15478                     * the remote call to initiate copy using temporary file.
15479                     */
15480                    ret = args.copyApk(mContainerService, true);
15481                }
15482            }
15483
15484            mRet = ret;
15485        }
15486
15487        @Override
15488        void handleReturnCode() {
15489            // If mArgs is null, then MCS couldn't be reached. When it
15490            // reconnects, it will try again to install. At that point, this
15491            // will succeed.
15492            if (mArgs != null) {
15493                processPendingInstall(mArgs, mRet);
15494            }
15495        }
15496
15497        @Override
15498        void handleServiceError() {
15499            mArgs = createInstallArgs(this);
15500            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15501        }
15502    }
15503
15504    private InstallArgs createInstallArgs(InstallParams params) {
15505        if (params.move != null) {
15506            return new MoveInstallArgs(params);
15507        } else {
15508            return new FileInstallArgs(params);
15509        }
15510    }
15511
15512    /**
15513     * Create args that describe an existing installed package. Typically used
15514     * when cleaning up old installs, or used as a move source.
15515     */
15516    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15517            String resourcePath, String[] instructionSets) {
15518        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15519    }
15520
15521    static abstract class InstallArgs {
15522        /** @see InstallParams#origin */
15523        final OriginInfo origin;
15524        /** @see InstallParams#move */
15525        final MoveInfo move;
15526
15527        final IPackageInstallObserver2 observer;
15528        // Always refers to PackageManager flags only
15529        final int installFlags;
15530        final String installerPackageName;
15531        final String volumeUuid;
15532        final UserHandle user;
15533        final String abiOverride;
15534        final String[] installGrantPermissions;
15535        /** If non-null, drop an async trace when the install completes */
15536        final String traceMethod;
15537        final int traceCookie;
15538        final PackageParser.SigningDetails signingDetails;
15539        final int installReason;
15540
15541        // The list of instruction sets supported by this app. This is currently
15542        // only used during the rmdex() phase to clean up resources. We can get rid of this
15543        // if we move dex files under the common app path.
15544        /* nullable */ String[] instructionSets;
15545
15546        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15547                int installFlags, String installerPackageName, String volumeUuid,
15548                UserHandle user, String[] instructionSets,
15549                String abiOverride, String[] installGrantPermissions,
15550                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15551                int installReason) {
15552            this.origin = origin;
15553            this.move = move;
15554            this.installFlags = installFlags;
15555            this.observer = observer;
15556            this.installerPackageName = installerPackageName;
15557            this.volumeUuid = volumeUuid;
15558            this.user = user;
15559            this.instructionSets = instructionSets;
15560            this.abiOverride = abiOverride;
15561            this.installGrantPermissions = installGrantPermissions;
15562            this.traceMethod = traceMethod;
15563            this.traceCookie = traceCookie;
15564            this.signingDetails = signingDetails;
15565            this.installReason = installReason;
15566        }
15567
15568        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15569        abstract int doPreInstall(int status);
15570
15571        /**
15572         * Rename package into final resting place. All paths on the given
15573         * scanned package should be updated to reflect the rename.
15574         */
15575        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15576        abstract int doPostInstall(int status, int uid);
15577
15578        /** @see PackageSettingBase#codePathString */
15579        abstract String getCodePath();
15580        /** @see PackageSettingBase#resourcePathString */
15581        abstract String getResourcePath();
15582
15583        // Need installer lock especially for dex file removal.
15584        abstract void cleanUpResourcesLI();
15585        abstract boolean doPostDeleteLI(boolean delete);
15586
15587        /**
15588         * Called before the source arguments are copied. This is used mostly
15589         * for MoveParams when it needs to read the source file to put it in the
15590         * destination.
15591         */
15592        int doPreCopy() {
15593            return PackageManager.INSTALL_SUCCEEDED;
15594        }
15595
15596        /**
15597         * Called after the source arguments are copied. This is used mostly for
15598         * MoveParams when it needs to read the source file to put it in the
15599         * destination.
15600         */
15601        int doPostCopy(int uid) {
15602            return PackageManager.INSTALL_SUCCEEDED;
15603        }
15604
15605        protected boolean isFwdLocked() {
15606            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15607        }
15608
15609        protected boolean isExternalAsec() {
15610            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15611        }
15612
15613        protected boolean isEphemeral() {
15614            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15615        }
15616
15617        UserHandle getUser() {
15618            return user;
15619        }
15620    }
15621
15622    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15623        if (!allCodePaths.isEmpty()) {
15624            if (instructionSets == null) {
15625                throw new IllegalStateException("instructionSet == null");
15626            }
15627            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15628            for (String codePath : allCodePaths) {
15629                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15630                    try {
15631                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15632                    } catch (InstallerException ignored) {
15633                    }
15634                }
15635            }
15636        }
15637    }
15638
15639    /**
15640     * Logic to handle installation of non-ASEC applications, including copying
15641     * and renaming logic.
15642     */
15643    class FileInstallArgs extends InstallArgs {
15644        private File codeFile;
15645        private File resourceFile;
15646
15647        // Example topology:
15648        // /data/app/com.example/base.apk
15649        // /data/app/com.example/split_foo.apk
15650        // /data/app/com.example/lib/arm/libfoo.so
15651        // /data/app/com.example/lib/arm64/libfoo.so
15652        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15653
15654        /** New install */
15655        FileInstallArgs(InstallParams params) {
15656            super(params.origin, params.move, params.observer, params.installFlags,
15657                    params.installerPackageName, params.volumeUuid,
15658                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15659                    params.grantedRuntimePermissions,
15660                    params.traceMethod, params.traceCookie, params.signingDetails,
15661                    params.installReason);
15662            if (isFwdLocked()) {
15663                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15664            }
15665        }
15666
15667        /** Existing install */
15668        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15669            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15670                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15671                    PackageManager.INSTALL_REASON_UNKNOWN);
15672            this.codeFile = (codePath != null) ? new File(codePath) : null;
15673            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15674        }
15675
15676        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15677            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15678            try {
15679                return doCopyApk(imcs, temp);
15680            } finally {
15681                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15682            }
15683        }
15684
15685        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15686            if (origin.staged) {
15687                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15688                codeFile = origin.file;
15689                resourceFile = origin.file;
15690                return PackageManager.INSTALL_SUCCEEDED;
15691            }
15692
15693            try {
15694                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15695                final File tempDir =
15696                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15697                codeFile = tempDir;
15698                resourceFile = tempDir;
15699            } catch (IOException e) {
15700                Slog.w(TAG, "Failed to create copy file: " + e);
15701                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15702            }
15703
15704            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15705                @Override
15706                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15707                    if (!FileUtils.isValidExtFilename(name)) {
15708                        throw new IllegalArgumentException("Invalid filename: " + name);
15709                    }
15710                    try {
15711                        final File file = new File(codeFile, name);
15712                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15713                                O_RDWR | O_CREAT, 0644);
15714                        Os.chmod(file.getAbsolutePath(), 0644);
15715                        return new ParcelFileDescriptor(fd);
15716                    } catch (ErrnoException e) {
15717                        throw new RemoteException("Failed to open: " + e.getMessage());
15718                    }
15719                }
15720            };
15721
15722            int ret = PackageManager.INSTALL_SUCCEEDED;
15723            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15724            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15725                Slog.e(TAG, "Failed to copy package");
15726                return ret;
15727            }
15728
15729            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15730            NativeLibraryHelper.Handle handle = null;
15731            try {
15732                handle = NativeLibraryHelper.Handle.create(codeFile);
15733                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15734                        abiOverride);
15735            } catch (IOException e) {
15736                Slog.e(TAG, "Copying native libraries failed", e);
15737                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15738            } finally {
15739                IoUtils.closeQuietly(handle);
15740            }
15741
15742            return ret;
15743        }
15744
15745        int doPreInstall(int status) {
15746            if (status != PackageManager.INSTALL_SUCCEEDED) {
15747                cleanUp();
15748            }
15749            return status;
15750        }
15751
15752        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15753            if (status != PackageManager.INSTALL_SUCCEEDED) {
15754                cleanUp();
15755                return false;
15756            }
15757
15758            final File targetDir = codeFile.getParentFile();
15759            final File beforeCodeFile = codeFile;
15760            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15761
15762            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15763            try {
15764                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15765            } catch (ErrnoException e) {
15766                Slog.w(TAG, "Failed to rename", e);
15767                return false;
15768            }
15769
15770            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15771                Slog.w(TAG, "Failed to restorecon");
15772                return false;
15773            }
15774
15775            // Reflect the rename internally
15776            codeFile = afterCodeFile;
15777            resourceFile = afterCodeFile;
15778
15779            // Reflect the rename in scanned details
15780            try {
15781                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15782            } catch (IOException e) {
15783                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15784                return false;
15785            }
15786            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15787                    afterCodeFile, pkg.baseCodePath));
15788            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15789                    afterCodeFile, pkg.splitCodePaths));
15790
15791            // Reflect the rename in app info
15792            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15793            pkg.setApplicationInfoCodePath(pkg.codePath);
15794            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15795            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15796            pkg.setApplicationInfoResourcePath(pkg.codePath);
15797            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15798            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15799
15800            return true;
15801        }
15802
15803        int doPostInstall(int status, int uid) {
15804            if (status != PackageManager.INSTALL_SUCCEEDED) {
15805                cleanUp();
15806            }
15807            return status;
15808        }
15809
15810        @Override
15811        String getCodePath() {
15812            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15813        }
15814
15815        @Override
15816        String getResourcePath() {
15817            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15818        }
15819
15820        private boolean cleanUp() {
15821            if (codeFile == null || !codeFile.exists()) {
15822                return false;
15823            }
15824
15825            removeCodePathLI(codeFile);
15826
15827            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15828                resourceFile.delete();
15829            }
15830
15831            return true;
15832        }
15833
15834        void cleanUpResourcesLI() {
15835            // Try enumerating all code paths before deleting
15836            List<String> allCodePaths = Collections.EMPTY_LIST;
15837            if (codeFile != null && codeFile.exists()) {
15838                try {
15839                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15840                    allCodePaths = pkg.getAllCodePaths();
15841                } catch (PackageParserException e) {
15842                    // Ignored; we tried our best
15843                }
15844            }
15845
15846            cleanUp();
15847            removeDexFiles(allCodePaths, instructionSets);
15848        }
15849
15850        boolean doPostDeleteLI(boolean delete) {
15851            // XXX err, shouldn't we respect the delete flag?
15852            cleanUpResourcesLI();
15853            return true;
15854        }
15855    }
15856
15857    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15858            PackageManagerException {
15859        if (copyRet < 0) {
15860            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15861                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15862                throw new PackageManagerException(copyRet, message);
15863            }
15864        }
15865    }
15866
15867    /**
15868     * Extract the StorageManagerService "container ID" from the full code path of an
15869     * .apk.
15870     */
15871    static String cidFromCodePath(String fullCodePath) {
15872        int eidx = fullCodePath.lastIndexOf("/");
15873        String subStr1 = fullCodePath.substring(0, eidx);
15874        int sidx = subStr1.lastIndexOf("/");
15875        return subStr1.substring(sidx+1, eidx);
15876    }
15877
15878    /**
15879     * Logic to handle movement of existing installed applications.
15880     */
15881    class MoveInstallArgs extends InstallArgs {
15882        private File codeFile;
15883        private File resourceFile;
15884
15885        /** New install */
15886        MoveInstallArgs(InstallParams params) {
15887            super(params.origin, params.move, params.observer, params.installFlags,
15888                    params.installerPackageName, params.volumeUuid,
15889                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15890                    params.grantedRuntimePermissions,
15891                    params.traceMethod, params.traceCookie, params.signingDetails,
15892                    params.installReason);
15893        }
15894
15895        int copyApk(IMediaContainerService imcs, boolean temp) {
15896            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15897                    + move.fromUuid + " to " + move.toUuid);
15898            synchronized (mInstaller) {
15899                try {
15900                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15901                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15902                } catch (InstallerException e) {
15903                    Slog.w(TAG, "Failed to move app", e);
15904                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15905                }
15906            }
15907
15908            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15909            resourceFile = codeFile;
15910            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15911
15912            return PackageManager.INSTALL_SUCCEEDED;
15913        }
15914
15915        int doPreInstall(int status) {
15916            if (status != PackageManager.INSTALL_SUCCEEDED) {
15917                cleanUp(move.toUuid);
15918            }
15919            return status;
15920        }
15921
15922        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15923            if (status != PackageManager.INSTALL_SUCCEEDED) {
15924                cleanUp(move.toUuid);
15925                return false;
15926            }
15927
15928            // Reflect the move in app info
15929            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15930            pkg.setApplicationInfoCodePath(pkg.codePath);
15931            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15932            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15933            pkg.setApplicationInfoResourcePath(pkg.codePath);
15934            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15935            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15936
15937            return true;
15938        }
15939
15940        int doPostInstall(int status, int uid) {
15941            if (status == PackageManager.INSTALL_SUCCEEDED) {
15942                cleanUp(move.fromUuid);
15943            } else {
15944                cleanUp(move.toUuid);
15945            }
15946            return status;
15947        }
15948
15949        @Override
15950        String getCodePath() {
15951            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15952        }
15953
15954        @Override
15955        String getResourcePath() {
15956            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15957        }
15958
15959        private boolean cleanUp(String volumeUuid) {
15960            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15961                    move.dataAppName);
15962            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15963            final int[] userIds = sUserManager.getUserIds();
15964            synchronized (mInstallLock) {
15965                // Clean up both app data and code
15966                // All package moves are frozen until finished
15967                for (int userId : userIds) {
15968                    try {
15969                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15970                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15971                    } catch (InstallerException e) {
15972                        Slog.w(TAG, String.valueOf(e));
15973                    }
15974                }
15975                removeCodePathLI(codeFile);
15976            }
15977            return true;
15978        }
15979
15980        void cleanUpResourcesLI() {
15981            throw new UnsupportedOperationException();
15982        }
15983
15984        boolean doPostDeleteLI(boolean delete) {
15985            throw new UnsupportedOperationException();
15986        }
15987    }
15988
15989    static String getAsecPackageName(String packageCid) {
15990        int idx = packageCid.lastIndexOf("-");
15991        if (idx == -1) {
15992            return packageCid;
15993        }
15994        return packageCid.substring(0, idx);
15995    }
15996
15997    // Utility method used to create code paths based on package name and available index.
15998    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15999        String idxStr = "";
16000        int idx = 1;
16001        // Fall back to default value of idx=1 if prefix is not
16002        // part of oldCodePath
16003        if (oldCodePath != null) {
16004            String subStr = oldCodePath;
16005            // Drop the suffix right away
16006            if (suffix != null && subStr.endsWith(suffix)) {
16007                subStr = subStr.substring(0, subStr.length() - suffix.length());
16008            }
16009            // If oldCodePath already contains prefix find out the
16010            // ending index to either increment or decrement.
16011            int sidx = subStr.lastIndexOf(prefix);
16012            if (sidx != -1) {
16013                subStr = subStr.substring(sidx + prefix.length());
16014                if (subStr != null) {
16015                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16016                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16017                    }
16018                    try {
16019                        idx = Integer.parseInt(subStr);
16020                        if (idx <= 1) {
16021                            idx++;
16022                        } else {
16023                            idx--;
16024                        }
16025                    } catch(NumberFormatException e) {
16026                    }
16027                }
16028            }
16029        }
16030        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16031        return prefix + idxStr;
16032    }
16033
16034    private File getNextCodePath(File targetDir, String packageName) {
16035        File result;
16036        SecureRandom random = new SecureRandom();
16037        byte[] bytes = new byte[16];
16038        do {
16039            random.nextBytes(bytes);
16040            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16041            result = new File(targetDir, packageName + "-" + suffix);
16042        } while (result.exists());
16043        return result;
16044    }
16045
16046    // Utility method that returns the relative package path with respect
16047    // to the installation directory. Like say for /data/data/com.test-1.apk
16048    // string com.test-1 is returned.
16049    static String deriveCodePathName(String codePath) {
16050        if (codePath == null) {
16051            return null;
16052        }
16053        final File codeFile = new File(codePath);
16054        final String name = codeFile.getName();
16055        if (codeFile.isDirectory()) {
16056            return name;
16057        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16058            final int lastDot = name.lastIndexOf('.');
16059            return name.substring(0, lastDot);
16060        } else {
16061            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16062            return null;
16063        }
16064    }
16065
16066    static class PackageInstalledInfo {
16067        String name;
16068        int uid;
16069        // The set of users that originally had this package installed.
16070        int[] origUsers;
16071        // The set of users that now have this package installed.
16072        int[] newUsers;
16073        PackageParser.Package pkg;
16074        int returnCode;
16075        String returnMsg;
16076        String installerPackageName;
16077        PackageRemovedInfo removedInfo;
16078        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16079
16080        public void setError(int code, String msg) {
16081            setReturnCode(code);
16082            setReturnMessage(msg);
16083            Slog.w(TAG, msg);
16084        }
16085
16086        public void setError(String msg, PackageParserException e) {
16087            setReturnCode(e.error);
16088            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16089            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16090            for (int i = 0; i < childCount; i++) {
16091                addedChildPackages.valueAt(i).setError(msg, e);
16092            }
16093            Slog.w(TAG, msg, e);
16094        }
16095
16096        public void setError(String msg, PackageManagerException e) {
16097            returnCode = e.error;
16098            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16099            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16100            for (int i = 0; i < childCount; i++) {
16101                addedChildPackages.valueAt(i).setError(msg, e);
16102            }
16103            Slog.w(TAG, msg, e);
16104        }
16105
16106        public void setReturnCode(int returnCode) {
16107            this.returnCode = returnCode;
16108            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16109            for (int i = 0; i < childCount; i++) {
16110                addedChildPackages.valueAt(i).returnCode = returnCode;
16111            }
16112        }
16113
16114        private void setReturnMessage(String returnMsg) {
16115            this.returnMsg = returnMsg;
16116            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16117            for (int i = 0; i < childCount; i++) {
16118                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16119            }
16120        }
16121
16122        // In some error cases we want to convey more info back to the observer
16123        String origPackage;
16124        String origPermission;
16125    }
16126
16127    /*
16128     * Install a non-existing package.
16129     */
16130    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16131            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16132            String volumeUuid, PackageInstalledInfo res, int installReason) {
16133        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16134
16135        // Remember this for later, in case we need to rollback this install
16136        String pkgName = pkg.packageName;
16137
16138        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16139
16140        synchronized(mPackages) {
16141            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16142            if (renamedPackage != null) {
16143                // A package with the same name is already installed, though
16144                // it has been renamed to an older name.  The package we
16145                // are trying to install should be installed as an update to
16146                // the existing one, but that has not been requested, so bail.
16147                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16148                        + " without first uninstalling package running as "
16149                        + renamedPackage);
16150                return;
16151            }
16152            if (mPackages.containsKey(pkgName)) {
16153                // Don't allow installation over an existing package with the same name.
16154                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16155                        + " without first uninstalling.");
16156                return;
16157            }
16158        }
16159
16160        try {
16161            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16162                    System.currentTimeMillis(), user);
16163
16164            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16165
16166            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16167                prepareAppDataAfterInstallLIF(newPackage);
16168
16169            } else {
16170                // Remove package from internal structures, but keep around any
16171                // data that might have already existed
16172                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16173                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16174            }
16175        } catch (PackageManagerException e) {
16176            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16177        }
16178
16179        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16180    }
16181
16182    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16183        try (DigestInputStream digestStream =
16184                new DigestInputStream(new FileInputStream(file), digest)) {
16185            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16186        }
16187    }
16188
16189    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16190            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16191            PackageInstalledInfo res, int installReason) {
16192        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16193
16194        final PackageParser.Package oldPackage;
16195        final PackageSetting ps;
16196        final String pkgName = pkg.packageName;
16197        final int[] allUsers;
16198        final int[] installedUsers;
16199
16200        synchronized(mPackages) {
16201            oldPackage = mPackages.get(pkgName);
16202            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16203
16204            // don't allow upgrade to target a release SDK from a pre-release SDK
16205            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16206                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16207            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16208                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16209            if (oldTargetsPreRelease
16210                    && !newTargetsPreRelease
16211                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16212                Slog.w(TAG, "Can't install package targeting released sdk");
16213                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16214                return;
16215            }
16216
16217            ps = mSettings.mPackages.get(pkgName);
16218
16219            // verify signatures are valid
16220            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16221            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16222                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16223                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16224                            "New package not signed by keys specified by upgrade-keysets: "
16225                                    + pkgName);
16226                    return;
16227                }
16228            } else {
16229
16230                // default to original signature matching
16231                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16232                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16233                                && !oldPackage.mSigningDetails.checkCapability(
16234                                        pkg.mSigningDetails,
16235                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16236                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16237                            "New package has a different signature: " + pkgName);
16238                    return;
16239                }
16240            }
16241
16242            // don't allow a system upgrade unless the upgrade hash matches
16243            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16244                byte[] digestBytes = null;
16245                try {
16246                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16247                    updateDigest(digest, new File(pkg.baseCodePath));
16248                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16249                        for (String path : pkg.splitCodePaths) {
16250                            updateDigest(digest, new File(path));
16251                        }
16252                    }
16253                    digestBytes = digest.digest();
16254                } catch (NoSuchAlgorithmException | IOException e) {
16255                    res.setError(INSTALL_FAILED_INVALID_APK,
16256                            "Could not compute hash: " + pkgName);
16257                    return;
16258                }
16259                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16260                    res.setError(INSTALL_FAILED_INVALID_APK,
16261                            "New package fails restrict-update check: " + pkgName);
16262                    return;
16263                }
16264                // retain upgrade restriction
16265                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16266            }
16267
16268            // Check for shared user id changes
16269            String invalidPackageName =
16270                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16271            if (invalidPackageName != null) {
16272                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16273                        "Package " + invalidPackageName + " tried to change user "
16274                                + oldPackage.mSharedUserId);
16275                return;
16276            }
16277
16278            // check if the new package supports all of the abis which the old package supports
16279            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16280            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16281            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16282                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16283                        "Update to package " + pkgName + " doesn't support multi arch");
16284                return;
16285            }
16286
16287            // In case of rollback, remember per-user/profile install state
16288            allUsers = sUserManager.getUserIds();
16289            installedUsers = ps.queryInstalledUsers(allUsers, true);
16290
16291            // don't allow an upgrade from full to ephemeral
16292            if (isInstantApp) {
16293                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16294                    for (int currentUser : allUsers) {
16295                        if (!ps.getInstantApp(currentUser)) {
16296                            // can't downgrade from full to instant
16297                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16298                                    + " for user: " + currentUser);
16299                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16300                            return;
16301                        }
16302                    }
16303                } else if (!ps.getInstantApp(user.getIdentifier())) {
16304                    // can't downgrade from full to instant
16305                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16306                            + " for user: " + user.getIdentifier());
16307                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16308                    return;
16309                }
16310            }
16311        }
16312
16313        // Update what is removed
16314        res.removedInfo = new PackageRemovedInfo(this);
16315        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16316        res.removedInfo.removedPackage = oldPackage.packageName;
16317        res.removedInfo.installerPackageName = ps.installerPackageName;
16318        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16319        res.removedInfo.isUpdate = true;
16320        res.removedInfo.origUsers = installedUsers;
16321        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16322        for (int i = 0; i < installedUsers.length; i++) {
16323            final int userId = installedUsers[i];
16324            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16325        }
16326
16327        final int childCount = (oldPackage.childPackages != null)
16328                ? oldPackage.childPackages.size() : 0;
16329        for (int i = 0; i < childCount; i++) {
16330            boolean childPackageUpdated = false;
16331            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16332            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16333            if (res.addedChildPackages != null) {
16334                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16335                if (childRes != null) {
16336                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16337                    childRes.removedInfo.removedPackage = childPkg.packageName;
16338                    if (childPs != null) {
16339                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16340                    }
16341                    childRes.removedInfo.isUpdate = true;
16342                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16343                    childPackageUpdated = true;
16344                }
16345            }
16346            if (!childPackageUpdated) {
16347                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16348                childRemovedRes.removedPackage = childPkg.packageName;
16349                if (childPs != null) {
16350                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16351                }
16352                childRemovedRes.isUpdate = false;
16353                childRemovedRes.dataRemoved = true;
16354                synchronized (mPackages) {
16355                    if (childPs != null) {
16356                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16357                    }
16358                }
16359                if (res.removedInfo.removedChildPackages == null) {
16360                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16361                }
16362                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16363            }
16364        }
16365
16366        boolean sysPkg = (isSystemApp(oldPackage));
16367        if (sysPkg) {
16368            // Set the system/privileged/oem/vendor/product flags as needed
16369            final boolean privileged =
16370                    (oldPackage.applicationInfo.privateFlags
16371                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16372            final boolean oem =
16373                    (oldPackage.applicationInfo.privateFlags
16374                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16375            final boolean vendor =
16376                    (oldPackage.applicationInfo.privateFlags
16377                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16378            final boolean product =
16379                    (oldPackage.applicationInfo.privateFlags
16380                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16381            final @ParseFlags int systemParseFlags = parseFlags;
16382            final @ScanFlags int systemScanFlags = scanFlags
16383                    | SCAN_AS_SYSTEM
16384                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16385                    | (oem ? SCAN_AS_OEM : 0)
16386                    | (vendor ? SCAN_AS_VENDOR : 0)
16387                    | (product ? SCAN_AS_PRODUCT : 0);
16388
16389            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16390                    user, allUsers, installerPackageName, res, installReason);
16391        } else {
16392            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16393                    user, allUsers, installerPackageName, res, installReason);
16394        }
16395    }
16396
16397    @Override
16398    public List<String> getPreviousCodePaths(String packageName) {
16399        final int callingUid = Binder.getCallingUid();
16400        final List<String> result = new ArrayList<>();
16401        if (getInstantAppPackageName(callingUid) != null) {
16402            return result;
16403        }
16404        final PackageSetting ps = mSettings.mPackages.get(packageName);
16405        if (ps != null
16406                && ps.oldCodePaths != null
16407                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16408            result.addAll(ps.oldCodePaths);
16409        }
16410        return result;
16411    }
16412
16413    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16414            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16415            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16416            String installerPackageName, PackageInstalledInfo res, int installReason) {
16417        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16418                + deletedPackage);
16419
16420        String pkgName = deletedPackage.packageName;
16421        boolean deletedPkg = true;
16422        boolean addedPkg = false;
16423        boolean updatedSettings = false;
16424        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16425        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16426                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16427
16428        final long origUpdateTime = (pkg.mExtras != null)
16429                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16430
16431        // First delete the existing package while retaining the data directory
16432        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16433                res.removedInfo, true, pkg)) {
16434            // If the existing package wasn't successfully deleted
16435            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16436            deletedPkg = false;
16437        } else {
16438            // Successfully deleted the old package; proceed with replace.
16439
16440            // If deleted package lived in a container, give users a chance to
16441            // relinquish resources before killing.
16442            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16443                if (DEBUG_INSTALL) {
16444                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16445                }
16446                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16447                final ArrayList<String> pkgList = new ArrayList<String>(1);
16448                pkgList.add(deletedPackage.applicationInfo.packageName);
16449                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16450            }
16451
16452            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16453                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16454
16455            try {
16456                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16457                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16458                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16459                        installReason);
16460
16461                // Update the in-memory copy of the previous code paths.
16462                PackageSetting ps = mSettings.mPackages.get(pkgName);
16463                if (!killApp) {
16464                    if (ps.oldCodePaths == null) {
16465                        ps.oldCodePaths = new ArraySet<>();
16466                    }
16467                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16468                    if (deletedPackage.splitCodePaths != null) {
16469                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16470                    }
16471                } else {
16472                    ps.oldCodePaths = null;
16473                }
16474                if (ps.childPackageNames != null) {
16475                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16476                        final String childPkgName = ps.childPackageNames.get(i);
16477                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16478                        childPs.oldCodePaths = ps.oldCodePaths;
16479                    }
16480                }
16481                prepareAppDataAfterInstallLIF(newPackage);
16482                addedPkg = true;
16483                mDexManager.notifyPackageUpdated(newPackage.packageName,
16484                        newPackage.baseCodePath, newPackage.splitCodePaths);
16485            } catch (PackageManagerException e) {
16486                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16487            }
16488        }
16489
16490        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16491            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16492
16493            // Revert all internal state mutations and added folders for the failed install
16494            if (addedPkg) {
16495                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16496                        res.removedInfo, true, null);
16497            }
16498
16499            // Restore the old package
16500            if (deletedPkg) {
16501                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16502                File restoreFile = new File(deletedPackage.codePath);
16503                // Parse old package
16504                boolean oldExternal = isExternal(deletedPackage);
16505                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16506                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16507                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16508                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16509                try {
16510                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16511                            null);
16512                } catch (PackageManagerException e) {
16513                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16514                            + e.getMessage());
16515                    return;
16516                }
16517
16518                synchronized (mPackages) {
16519                    // Ensure the installer package name up to date
16520                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16521
16522                    // Update permissions for restored package
16523                    mPermissionManager.updatePermissions(
16524                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16525                            mPermissionCallback);
16526
16527                    mSettings.writeLPr();
16528                }
16529
16530                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16531            }
16532        } else {
16533            synchronized (mPackages) {
16534                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16535                if (ps != null) {
16536                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16537                    if (res.removedInfo.removedChildPackages != null) {
16538                        final int childCount = res.removedInfo.removedChildPackages.size();
16539                        // Iterate in reverse as we may modify the collection
16540                        for (int i = childCount - 1; i >= 0; i--) {
16541                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16542                            if (res.addedChildPackages.containsKey(childPackageName)) {
16543                                res.removedInfo.removedChildPackages.removeAt(i);
16544                            } else {
16545                                PackageRemovedInfo childInfo = res.removedInfo
16546                                        .removedChildPackages.valueAt(i);
16547                                childInfo.removedForAllUsers = mPackages.get(
16548                                        childInfo.removedPackage) == null;
16549                            }
16550                        }
16551                    }
16552                }
16553            }
16554        }
16555    }
16556
16557    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16558            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16559            final @ScanFlags int scanFlags, UserHandle user,
16560            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16561            int installReason) {
16562        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16563                + ", old=" + deletedPackage);
16564
16565        final boolean disabledSystem;
16566
16567        // Remove existing system package
16568        removePackageLI(deletedPackage, true);
16569
16570        synchronized (mPackages) {
16571            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16572        }
16573        if (!disabledSystem) {
16574            // We didn't need to disable the .apk as a current system package,
16575            // which means we are replacing another update that is already
16576            // installed.  We need to make sure to delete the older one's .apk.
16577            res.removedInfo.args = createInstallArgsForExisting(0,
16578                    deletedPackage.applicationInfo.getCodePath(),
16579                    deletedPackage.applicationInfo.getResourcePath(),
16580                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16581        } else {
16582            res.removedInfo.args = null;
16583        }
16584
16585        // Successfully disabled the old package. Now proceed with re-installation
16586        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16587                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16588
16589        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16590        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16591                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16592
16593        PackageParser.Package newPackage = null;
16594        try {
16595            // Add the package to the internal data structures
16596            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16597
16598            // Set the update and install times
16599            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16600            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16601                    System.currentTimeMillis());
16602
16603            // Update the package dynamic state if succeeded
16604            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16605                // Now that the install succeeded make sure we remove data
16606                // directories for any child package the update removed.
16607                final int deletedChildCount = (deletedPackage.childPackages != null)
16608                        ? deletedPackage.childPackages.size() : 0;
16609                final int newChildCount = (newPackage.childPackages != null)
16610                        ? newPackage.childPackages.size() : 0;
16611                for (int i = 0; i < deletedChildCount; i++) {
16612                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16613                    boolean childPackageDeleted = true;
16614                    for (int j = 0; j < newChildCount; j++) {
16615                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16616                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16617                            childPackageDeleted = false;
16618                            break;
16619                        }
16620                    }
16621                    if (childPackageDeleted) {
16622                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16623                                deletedChildPkg.packageName);
16624                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16625                            PackageRemovedInfo removedChildRes = res.removedInfo
16626                                    .removedChildPackages.get(deletedChildPkg.packageName);
16627                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16628                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16629                        }
16630                    }
16631                }
16632
16633                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16634                        installReason);
16635                prepareAppDataAfterInstallLIF(newPackage);
16636
16637                mDexManager.notifyPackageUpdated(newPackage.packageName,
16638                            newPackage.baseCodePath, newPackage.splitCodePaths);
16639            }
16640        } catch (PackageManagerException e) {
16641            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16642            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16643        }
16644
16645        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16646            // Re installation failed. Restore old information
16647            // Remove new pkg information
16648            if (newPackage != null) {
16649                removeInstalledPackageLI(newPackage, true);
16650            }
16651            // Add back the old system package
16652            try {
16653                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16654            } catch (PackageManagerException e) {
16655                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16656            }
16657
16658            synchronized (mPackages) {
16659                if (disabledSystem) {
16660                    enableSystemPackageLPw(deletedPackage);
16661                }
16662
16663                // Ensure the installer package name up to date
16664                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16665
16666                // Update permissions for restored package
16667                mPermissionManager.updatePermissions(
16668                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16669                        mPermissionCallback);
16670
16671                mSettings.writeLPr();
16672            }
16673
16674            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16675                    + " after failed upgrade");
16676        }
16677    }
16678
16679    /**
16680     * Checks whether the parent or any of the child packages have a change shared
16681     * user. For a package to be a valid update the shred users of the parent and
16682     * the children should match. We may later support changing child shared users.
16683     * @param oldPkg The updated package.
16684     * @param newPkg The update package.
16685     * @return The shared user that change between the versions.
16686     */
16687    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16688            PackageParser.Package newPkg) {
16689        // Check parent shared user
16690        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16691            return newPkg.packageName;
16692        }
16693        // Check child shared users
16694        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16695        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16696        for (int i = 0; i < newChildCount; i++) {
16697            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16698            // If this child was present, did it have the same shared user?
16699            for (int j = 0; j < oldChildCount; j++) {
16700                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16701                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16702                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16703                    return newChildPkg.packageName;
16704                }
16705            }
16706        }
16707        return null;
16708    }
16709
16710    private void removeNativeBinariesLI(PackageSetting ps) {
16711        // Remove the lib path for the parent package
16712        if (ps != null) {
16713            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16714            // Remove the lib path for the child packages
16715            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16716            for (int i = 0; i < childCount; i++) {
16717                PackageSetting childPs = null;
16718                synchronized (mPackages) {
16719                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16720                }
16721                if (childPs != null) {
16722                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16723                            .legacyNativeLibraryPathString);
16724                }
16725            }
16726        }
16727    }
16728
16729    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16730        // Enable the parent package
16731        mSettings.enableSystemPackageLPw(pkg.packageName);
16732        // Enable the child packages
16733        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16734        for (int i = 0; i < childCount; i++) {
16735            PackageParser.Package childPkg = pkg.childPackages.get(i);
16736            mSettings.enableSystemPackageLPw(childPkg.packageName);
16737        }
16738    }
16739
16740    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16741            PackageParser.Package newPkg) {
16742        // Disable the parent package (parent always replaced)
16743        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16744        // Disable the child packages
16745        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16746        for (int i = 0; i < childCount; i++) {
16747            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16748            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16749            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16750        }
16751        return disabled;
16752    }
16753
16754    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16755            String installerPackageName) {
16756        // Enable the parent package
16757        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16758        // Enable the child packages
16759        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16760        for (int i = 0; i < childCount; i++) {
16761            PackageParser.Package childPkg = pkg.childPackages.get(i);
16762            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16763        }
16764    }
16765
16766    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16767            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16768        // Update the parent package setting
16769        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16770                res, user, installReason);
16771        // Update the child packages setting
16772        final int childCount = (newPackage.childPackages != null)
16773                ? newPackage.childPackages.size() : 0;
16774        for (int i = 0; i < childCount; i++) {
16775            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16776            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16777            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16778                    childRes.origUsers, childRes, user, installReason);
16779        }
16780    }
16781
16782    private void updateSettingsInternalLI(PackageParser.Package pkg,
16783            String installerPackageName, int[] allUsers, int[] installedForUsers,
16784            PackageInstalledInfo res, UserHandle user, int installReason) {
16785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16786
16787        final String pkgName = pkg.packageName;
16788
16789        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16790        synchronized (mPackages) {
16791// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16792            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16793                    mPermissionCallback);
16794            // For system-bundled packages, we assume that installing an upgraded version
16795            // of the package implies that the user actually wants to run that new code,
16796            // so we enable the package.
16797            PackageSetting ps = mSettings.mPackages.get(pkgName);
16798            final int userId = user.getIdentifier();
16799            if (ps != null) {
16800                if (isSystemApp(pkg)) {
16801                    if (DEBUG_INSTALL) {
16802                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16803                    }
16804                    // Enable system package for requested users
16805                    if (res.origUsers != null) {
16806                        for (int origUserId : res.origUsers) {
16807                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16808                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16809                                        origUserId, installerPackageName);
16810                            }
16811                        }
16812                    }
16813                    // Also convey the prior install/uninstall state
16814                    if (allUsers != null && installedForUsers != null) {
16815                        for (int currentUserId : allUsers) {
16816                            final boolean installed = ArrayUtils.contains(
16817                                    installedForUsers, currentUserId);
16818                            if (DEBUG_INSTALL) {
16819                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16820                            }
16821                            ps.setInstalled(installed, currentUserId);
16822                        }
16823                        // these install state changes will be persisted in the
16824                        // upcoming call to mSettings.writeLPr().
16825                    }
16826                }
16827                // It's implied that when a user requests installation, they want the app to be
16828                // installed and enabled.
16829                if (userId != UserHandle.USER_ALL) {
16830                    ps.setInstalled(true, userId);
16831                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16832                }
16833
16834                // When replacing an existing package, preserve the original install reason for all
16835                // users that had the package installed before.
16836                final Set<Integer> previousUserIds = new ArraySet<>();
16837                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16838                    final int installReasonCount = res.removedInfo.installReasons.size();
16839                    for (int i = 0; i < installReasonCount; i++) {
16840                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16841                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16842                        ps.setInstallReason(previousInstallReason, previousUserId);
16843                        previousUserIds.add(previousUserId);
16844                    }
16845                }
16846
16847                // Set install reason for users that are having the package newly installed.
16848                if (userId == UserHandle.USER_ALL) {
16849                    for (int currentUserId : sUserManager.getUserIds()) {
16850                        if (!previousUserIds.contains(currentUserId)) {
16851                            ps.setInstallReason(installReason, currentUserId);
16852                        }
16853                    }
16854                } else if (!previousUserIds.contains(userId)) {
16855                    ps.setInstallReason(installReason, userId);
16856                }
16857                mSettings.writeKernelMappingLPr(ps);
16858            }
16859            res.name = pkgName;
16860            res.uid = pkg.applicationInfo.uid;
16861            res.pkg = pkg;
16862            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16863            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16864            //to update install status
16865            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16866            mSettings.writeLPr();
16867            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16868        }
16869
16870        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16871    }
16872
16873    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16874        try {
16875            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16876            installPackageLI(args, res);
16877        } finally {
16878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16879        }
16880    }
16881
16882    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16883        final int installFlags = args.installFlags;
16884        final String installerPackageName = args.installerPackageName;
16885        final String volumeUuid = args.volumeUuid;
16886        final File tmpPackageFile = new File(args.getCodePath());
16887        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16888        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16889                || (args.volumeUuid != null));
16890        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16891        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16892        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16893        final boolean virtualPreload =
16894                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16895        boolean replace = false;
16896        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16897        if (args.move != null) {
16898            // moving a complete application; perform an initial scan on the new install location
16899            scanFlags |= SCAN_INITIAL;
16900        }
16901        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16902            scanFlags |= SCAN_DONT_KILL_APP;
16903        }
16904        if (instantApp) {
16905            scanFlags |= SCAN_AS_INSTANT_APP;
16906        }
16907        if (fullApp) {
16908            scanFlags |= SCAN_AS_FULL_APP;
16909        }
16910        if (virtualPreload) {
16911            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16912        }
16913
16914        // Result object to be returned
16915        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16916        res.installerPackageName = installerPackageName;
16917
16918        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16919
16920        // Sanity check
16921        if (instantApp && (forwardLocked || onExternal)) {
16922            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16923                    + " external=" + onExternal);
16924            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16925            return;
16926        }
16927
16928        // Retrieve PackageSettings and parse package
16929        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16930                | PackageParser.PARSE_ENFORCE_CODE
16931                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16932                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16933                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16934        PackageParser pp = new PackageParser();
16935        pp.setSeparateProcesses(mSeparateProcesses);
16936        pp.setDisplayMetrics(mMetrics);
16937        pp.setCallback(mPackageParserCallback);
16938
16939        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16940        final PackageParser.Package pkg;
16941        try {
16942            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16943            DexMetadataHelper.validatePackageDexMetadata(pkg);
16944        } catch (PackageParserException e) {
16945            res.setError("Failed parse during installPackageLI", e);
16946            return;
16947        } finally {
16948            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16949        }
16950
16951        // Instant apps have several additional install-time checks.
16952        if (instantApp) {
16953            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16954                Slog.w(TAG,
16955                        "Instant app package " + pkg.packageName + " does not target at least O");
16956                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16957                        "Instant app package must target at least O");
16958                return;
16959            }
16960            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16961                Slog.w(TAG, "Instant app package " + pkg.packageName
16962                        + " does not target targetSandboxVersion 2");
16963                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16964                        "Instant app package must use targetSandboxVersion 2");
16965                return;
16966            }
16967            if (pkg.mSharedUserId != null) {
16968                Slog.w(TAG, "Instant app package " + pkg.packageName
16969                        + " may not declare sharedUserId.");
16970                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16971                        "Instant app package may not declare a sharedUserId");
16972                return;
16973            }
16974        }
16975
16976        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16977            // Static shared libraries have synthetic package names
16978            renameStaticSharedLibraryPackage(pkg);
16979
16980            // No static shared libs on external storage
16981            if (onExternal) {
16982                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16983                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16984                        "Packages declaring static-shared libs cannot be updated");
16985                return;
16986            }
16987        }
16988
16989        // If we are installing a clustered package add results for the children
16990        if (pkg.childPackages != null) {
16991            synchronized (mPackages) {
16992                final int childCount = pkg.childPackages.size();
16993                for (int i = 0; i < childCount; i++) {
16994                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16995                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16996                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16997                    childRes.pkg = childPkg;
16998                    childRes.name = childPkg.packageName;
16999                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17000                    if (childPs != null) {
17001                        childRes.origUsers = childPs.queryInstalledUsers(
17002                                sUserManager.getUserIds(), true);
17003                    }
17004                    if ((mPackages.containsKey(childPkg.packageName))) {
17005                        childRes.removedInfo = new PackageRemovedInfo(this);
17006                        childRes.removedInfo.removedPackage = childPkg.packageName;
17007                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17008                    }
17009                    if (res.addedChildPackages == null) {
17010                        res.addedChildPackages = new ArrayMap<>();
17011                    }
17012                    res.addedChildPackages.put(childPkg.packageName, childRes);
17013                }
17014            }
17015        }
17016
17017        // If package doesn't declare API override, mark that we have an install
17018        // time CPU ABI override.
17019        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17020            pkg.cpuAbiOverride = args.abiOverride;
17021        }
17022
17023        String pkgName = res.name = pkg.packageName;
17024        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17025            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17026                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17027                return;
17028            }
17029        }
17030
17031        try {
17032            // either use what we've been given or parse directly from the APK
17033            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17034                pkg.setSigningDetails(args.signingDetails);
17035            } else {
17036                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17037            }
17038        } catch (PackageParserException e) {
17039            res.setError("Failed collect during installPackageLI", e);
17040            return;
17041        }
17042
17043        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17044                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17045            Slog.w(TAG, "Instant app package " + pkg.packageName
17046                    + " is not signed with at least APK Signature Scheme v2");
17047            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17048                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17049            return;
17050        }
17051
17052        // Get rid of all references to package scan path via parser.
17053        pp = null;
17054        String oldCodePath = null;
17055        boolean systemApp = false;
17056        synchronized (mPackages) {
17057            // Check if installing already existing package
17058            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17059                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17060                if (pkg.mOriginalPackages != null
17061                        && pkg.mOriginalPackages.contains(oldName)
17062                        && mPackages.containsKey(oldName)) {
17063                    // This package is derived from an original package,
17064                    // and this device has been updating from that original
17065                    // name.  We must continue using the original name, so
17066                    // rename the new package here.
17067                    pkg.setPackageName(oldName);
17068                    pkgName = pkg.packageName;
17069                    replace = true;
17070                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17071                            + oldName + " pkgName=" + pkgName);
17072                } else if (mPackages.containsKey(pkgName)) {
17073                    // This package, under its official name, already exists
17074                    // on the device; we should replace it.
17075                    replace = true;
17076                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17077                }
17078
17079                // Child packages are installed through the parent package
17080                if (pkg.parentPackage != null) {
17081                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17082                            "Package " + pkg.packageName + " is child of package "
17083                                    + pkg.parentPackage.parentPackage + ". Child packages "
17084                                    + "can be updated only through the parent package.");
17085                    return;
17086                }
17087
17088                if (replace) {
17089                    // Prevent apps opting out from runtime permissions
17090                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17091                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17092                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17093                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17094                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17095                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17096                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17097                                        + " doesn't support runtime permissions but the old"
17098                                        + " target SDK " + oldTargetSdk + " does.");
17099                        return;
17100                    }
17101                    // Prevent persistent apps from being updated
17102                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17103                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17104                                "Package " + oldPackage.packageName + " is a persistent app. "
17105                                        + "Persistent apps are not updateable.");
17106                        return;
17107                    }
17108                    // Prevent apps from downgrading their targetSandbox.
17109                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17110                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17111                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17112                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17113                                "Package " + pkg.packageName + " new target sandbox "
17114                                + newTargetSandbox + " is incompatible with the previous value of"
17115                                + oldTargetSandbox + ".");
17116                        return;
17117                    }
17118
17119                    // Prevent installing of child packages
17120                    if (oldPackage.parentPackage != null) {
17121                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17122                                "Package " + pkg.packageName + " is child of package "
17123                                        + oldPackage.parentPackage + ". Child packages "
17124                                        + "can be updated only through the parent package.");
17125                        return;
17126                    }
17127                }
17128            }
17129
17130            PackageSetting ps = mSettings.mPackages.get(pkgName);
17131            if (ps != null) {
17132                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17133
17134                // Static shared libs have same package with different versions where
17135                // we internally use a synthetic package name to allow multiple versions
17136                // of the same package, therefore we need to compare signatures against
17137                // the package setting for the latest library version.
17138                PackageSetting signatureCheckPs = ps;
17139                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17140                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17141                    if (libraryEntry != null) {
17142                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17143                    }
17144                }
17145
17146                // Quick sanity check that we're signed correctly if updating;
17147                // we'll check this again later when scanning, but we want to
17148                // bail early here before tripping over redefined permissions.
17149                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17150                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17151                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17152                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17153                                + pkg.packageName + " upgrade keys do not match the "
17154                                + "previously installed version");
17155                        return;
17156                    }
17157                } else {
17158                    try {
17159                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17160                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17161                        // We don't care about disabledPkgSetting on install for now.
17162                        final boolean compatMatch = verifySignatures(
17163                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17164                                compareRecover);
17165                        // The new KeySets will be re-added later in the scanning process.
17166                        if (compatMatch) {
17167                            synchronized (mPackages) {
17168                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17169                            }
17170                        }
17171                    } catch (PackageManagerException e) {
17172                        res.setError(e.error, e.getMessage());
17173                        return;
17174                    }
17175                }
17176
17177                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17178                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17179                    systemApp = (ps.pkg.applicationInfo.flags &
17180                            ApplicationInfo.FLAG_SYSTEM) != 0;
17181                }
17182                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17183            }
17184
17185            int N = pkg.permissions.size();
17186            for (int i = N-1; i >= 0; i--) {
17187                final PackageParser.Permission perm = pkg.permissions.get(i);
17188                final BasePermission bp =
17189                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17190
17191                // Don't allow anyone but the system to define ephemeral permissions.
17192                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17193                        && !systemApp) {
17194                    Slog.w(TAG, "Non-System package " + pkg.packageName
17195                            + " attempting to delcare ephemeral permission "
17196                            + perm.info.name + "; Removing ephemeral.");
17197                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17198                }
17199
17200                // Check whether the newly-scanned package wants to define an already-defined perm
17201                if (bp != null) {
17202                    // If the defining package is signed with our cert, it's okay.  This
17203                    // also includes the "updating the same package" case, of course.
17204                    // "updating same package" could also involve key-rotation.
17205                    final boolean sigsOk;
17206                    final String sourcePackageName = bp.getSourcePackageName();
17207                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17208                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17209                    if (sourcePackageName.equals(pkg.packageName)
17210                            && (ksms.shouldCheckUpgradeKeySetLocked(
17211                                    sourcePackageSetting, scanFlags))) {
17212                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17213                    } else {
17214
17215                        // in the event of signing certificate rotation, we need to see if the
17216                        // package's certificate has rotated from the current one, or if it is an
17217                        // older certificate with which the current is ok with sharing permissions
17218                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17219                                        pkg.mSigningDetails,
17220                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17221                            sigsOk = true;
17222                        } else if (pkg.mSigningDetails.checkCapability(
17223                                        sourcePackageSetting.signatures.mSigningDetails,
17224                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17225
17226                            // the scanned package checks out, has signing certificate rotation
17227                            // history, and is newer; bring it over
17228                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17229                            sigsOk = true;
17230                        } else {
17231                            sigsOk = false;
17232                        }
17233                    }
17234                    if (!sigsOk) {
17235                        // If the owning package is the system itself, we log but allow
17236                        // install to proceed; we fail the install on all other permission
17237                        // redefinitions.
17238                        if (!sourcePackageName.equals("android")) {
17239                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17240                                    + pkg.packageName + " attempting to redeclare permission "
17241                                    + perm.info.name + " already owned by " + sourcePackageName);
17242                            res.origPermission = perm.info.name;
17243                            res.origPackage = sourcePackageName;
17244                            return;
17245                        } else {
17246                            Slog.w(TAG, "Package " + pkg.packageName
17247                                    + " attempting to redeclare system permission "
17248                                    + perm.info.name + "; ignoring new declaration");
17249                            pkg.permissions.remove(i);
17250                        }
17251                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17252                        // Prevent apps to change protection level to dangerous from any other
17253                        // type as this would allow a privilege escalation where an app adds a
17254                        // normal/signature permission in other app's group and later redefines
17255                        // it as dangerous leading to the group auto-grant.
17256                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17257                                == PermissionInfo.PROTECTION_DANGEROUS) {
17258                            if (bp != null && !bp.isRuntime()) {
17259                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17260                                        + "non-runtime permission " + perm.info.name
17261                                        + " to runtime; keeping old protection level");
17262                                perm.info.protectionLevel = bp.getProtectionLevel();
17263                            }
17264                        }
17265                    }
17266                }
17267            }
17268        }
17269
17270        if (systemApp) {
17271            if (onExternal) {
17272                // Abort update; system app can't be replaced with app on sdcard
17273                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17274                        "Cannot install updates to system apps on sdcard");
17275                return;
17276            } else if (instantApp) {
17277                // Abort update; system app can't be replaced with an instant app
17278                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17279                        "Cannot update a system app with an instant app");
17280                return;
17281            }
17282        }
17283
17284        if (args.move != null) {
17285            // We did an in-place move, so dex is ready to roll
17286            scanFlags |= SCAN_NO_DEX;
17287            scanFlags |= SCAN_MOVE;
17288
17289            synchronized (mPackages) {
17290                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17291                if (ps == null) {
17292                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17293                            "Missing settings for moved package " + pkgName);
17294                }
17295
17296                // We moved the entire application as-is, so bring over the
17297                // previously derived ABI information.
17298                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17299                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17300            }
17301
17302        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17303            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17304            scanFlags |= SCAN_NO_DEX;
17305
17306            try {
17307                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17308                    args.abiOverride : pkg.cpuAbiOverride);
17309                final boolean extractNativeLibs = !pkg.isLibrary();
17310                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17311            } catch (PackageManagerException pme) {
17312                Slog.e(TAG, "Error deriving application ABI", pme);
17313                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17314                return;
17315            }
17316
17317            // Shared libraries for the package need to be updated.
17318            synchronized (mPackages) {
17319                try {
17320                    updateSharedLibrariesLPr(pkg, null);
17321                } catch (PackageManagerException e) {
17322                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17323                }
17324            }
17325        }
17326
17327        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17328            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17329            return;
17330        }
17331
17332        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17333            String apkPath = null;
17334            synchronized (mPackages) {
17335                // Note that if the attacker managed to skip verify setup, for example by tampering
17336                // with the package settings, upon reboot we will do full apk verification when
17337                // verity is not detected.
17338                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17339                if (ps != null && ps.isPrivileged()) {
17340                    apkPath = pkg.baseCodePath;
17341                }
17342            }
17343
17344            if (apkPath != null) {
17345                final VerityUtils.SetupResult result =
17346                        VerityUtils.generateApkVeritySetupData(apkPath);
17347                if (result.isOk()) {
17348                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17349                    FileDescriptor fd = result.getUnownedFileDescriptor();
17350                    try {
17351                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17352                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17353                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17354                    } catch (InstallerException | IOException | DigestException |
17355                             NoSuchAlgorithmException e) {
17356                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17357                                "Failed to set up verity: " + e);
17358                        return;
17359                    } finally {
17360                        IoUtils.closeQuietly(fd);
17361                    }
17362                } else if (result.isFailed()) {
17363                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17364                    return;
17365                } else {
17366                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17367                    // reboot.
17368                }
17369            }
17370        }
17371
17372        if (!instantApp) {
17373            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17374        } else {
17375            if (DEBUG_DOMAIN_VERIFICATION) {
17376                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17377            }
17378        }
17379
17380        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17381                "installPackageLI")) {
17382            if (replace) {
17383                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17384                    // Static libs have a synthetic package name containing the version
17385                    // and cannot be updated as an update would get a new package name,
17386                    // unless this is the exact same version code which is useful for
17387                    // development.
17388                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17389                    if (existingPkg != null &&
17390                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17391                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17392                                + "static-shared libs cannot be updated");
17393                        return;
17394                    }
17395                }
17396                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17397                        installerPackageName, res, args.installReason);
17398            } else {
17399                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17400                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17401            }
17402        }
17403
17404        // Prepare the application profiles for the new code paths.
17405        // This needs to be done before invoking dexopt so that any install-time profile
17406        // can be used for optimizations.
17407        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17408
17409        // Check whether we need to dexopt the app.
17410        //
17411        // NOTE: it is IMPORTANT to call dexopt:
17412        //   - after doRename which will sync the package data from PackageParser.Package and its
17413        //     corresponding ApplicationInfo.
17414        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17415        //     uid of the application (pkg.applicationInfo.uid).
17416        //     This update happens in place!
17417        //
17418        // We only need to dexopt if the package meets ALL of the following conditions:
17419        //   1) it is not forward locked.
17420        //   2) it is not on on an external ASEC container.
17421        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17422        //
17423        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17424        // complete, so we skip this step during installation. Instead, we'll take extra time
17425        // the first time the instant app starts. It's preferred to do it this way to provide
17426        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17427        // middle of running an instant app. The default behaviour can be overridden
17428        // via gservices.
17429        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17430                && !forwardLocked
17431                && !pkg.applicationInfo.isExternalAsec()
17432                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17433                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17434
17435        if (performDexopt) {
17436            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17437            // Do not run PackageDexOptimizer through the local performDexOpt
17438            // method because `pkg` may not be in `mPackages` yet.
17439            //
17440            // Also, don't fail application installs if the dexopt step fails.
17441            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17442                    REASON_INSTALL,
17443                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17444                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17445            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17446                    null /* instructionSets */,
17447                    getOrCreateCompilerPackageStats(pkg),
17448                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17449                    dexoptOptions);
17450            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17451        }
17452
17453        // Notify BackgroundDexOptService that the package has been changed.
17454        // If this is an update of a package which used to fail to compile,
17455        // BackgroundDexOptService will remove it from its blacklist.
17456        // TODO: Layering violation
17457        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17458
17459        synchronized (mPackages) {
17460            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17461            if (ps != null) {
17462                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17463                ps.setUpdateAvailable(false /*updateAvailable*/);
17464            }
17465
17466            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17467            for (int i = 0; i < childCount; i++) {
17468                PackageParser.Package childPkg = pkg.childPackages.get(i);
17469                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17470                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17471                if (childPs != null) {
17472                    childRes.newUsers = childPs.queryInstalledUsers(
17473                            sUserManager.getUserIds(), true);
17474                }
17475            }
17476
17477            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17478                updateSequenceNumberLP(ps, res.newUsers);
17479                updateInstantAppInstallerLocked(pkgName);
17480            }
17481        }
17482    }
17483
17484    private void startIntentFilterVerifications(int userId, boolean replacing,
17485            PackageParser.Package pkg) {
17486        if (mIntentFilterVerifierComponent == null) {
17487            Slog.w(TAG, "No IntentFilter verification will not be done as "
17488                    + "there is no IntentFilterVerifier available!");
17489            return;
17490        }
17491
17492        final int verifierUid = getPackageUid(
17493                mIntentFilterVerifierComponent.getPackageName(),
17494                MATCH_DEBUG_TRIAGED_MISSING,
17495                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17496
17497        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17498        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17499        mHandler.sendMessage(msg);
17500
17501        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17502        for (int i = 0; i < childCount; i++) {
17503            PackageParser.Package childPkg = pkg.childPackages.get(i);
17504            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17505            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17506            mHandler.sendMessage(msg);
17507        }
17508    }
17509
17510    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17511            PackageParser.Package pkg) {
17512        int size = pkg.activities.size();
17513        if (size == 0) {
17514            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17515                    "No activity, so no need to verify any IntentFilter!");
17516            return;
17517        }
17518
17519        final boolean hasDomainURLs = hasDomainURLs(pkg);
17520        if (!hasDomainURLs) {
17521            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17522                    "No domain URLs, so no need to verify any IntentFilter!");
17523            return;
17524        }
17525
17526        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17527                + " if any IntentFilter from the " + size
17528                + " Activities needs verification ...");
17529
17530        int count = 0;
17531        final String packageName = pkg.packageName;
17532
17533        synchronized (mPackages) {
17534            // If this is a new install and we see that we've already run verification for this
17535            // package, we have nothing to do: it means the state was restored from backup.
17536            if (!replacing) {
17537                IntentFilterVerificationInfo ivi =
17538                        mSettings.getIntentFilterVerificationLPr(packageName);
17539                if (ivi != null) {
17540                    if (DEBUG_DOMAIN_VERIFICATION) {
17541                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17542                                + ivi.getStatusString());
17543                    }
17544                    return;
17545                }
17546            }
17547
17548            // If any filters need to be verified, then all need to be.
17549            boolean needToVerify = false;
17550            for (PackageParser.Activity a : pkg.activities) {
17551                for (ActivityIntentInfo filter : a.intents) {
17552                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17553                        if (DEBUG_DOMAIN_VERIFICATION) {
17554                            Slog.d(TAG,
17555                                    "Intent filter needs verification, so processing all filters");
17556                        }
17557                        needToVerify = true;
17558                        break;
17559                    }
17560                }
17561            }
17562
17563            if (needToVerify) {
17564                final int verificationId = mIntentFilterVerificationToken++;
17565                for (PackageParser.Activity a : pkg.activities) {
17566                    for (ActivityIntentInfo filter : a.intents) {
17567                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17568                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17569                                    "Verification needed for IntentFilter:" + filter.toString());
17570                            mIntentFilterVerifier.addOneIntentFilterVerification(
17571                                    verifierUid, userId, verificationId, filter, packageName);
17572                            count++;
17573                        }
17574                    }
17575                }
17576            }
17577        }
17578
17579        if (count > 0) {
17580            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17581                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17582                    +  " for userId:" + userId);
17583            mIntentFilterVerifier.startVerifications(userId);
17584        } else {
17585            if (DEBUG_DOMAIN_VERIFICATION) {
17586                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17587            }
17588        }
17589    }
17590
17591    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17592        final ComponentName cn  = filter.activity.getComponentName();
17593        final String packageName = cn.getPackageName();
17594
17595        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17596                packageName);
17597        if (ivi == null) {
17598            return true;
17599        }
17600        int status = ivi.getStatus();
17601        switch (status) {
17602            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17603            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17604                return true;
17605
17606            default:
17607                // Nothing to do
17608                return false;
17609        }
17610    }
17611
17612    private static boolean isMultiArch(ApplicationInfo info) {
17613        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17614    }
17615
17616    private static boolean isExternal(PackageParser.Package pkg) {
17617        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17618    }
17619
17620    private static boolean isExternal(PackageSetting ps) {
17621        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17622    }
17623
17624    private static boolean isSystemApp(PackageParser.Package pkg) {
17625        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17626    }
17627
17628    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17629        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17630    }
17631
17632    private static boolean isOemApp(PackageParser.Package pkg) {
17633        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17634    }
17635
17636    private static boolean isVendorApp(PackageParser.Package pkg) {
17637        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17638    }
17639
17640    private static boolean isProductApp(PackageParser.Package pkg) {
17641        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17642    }
17643
17644    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17645        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17646    }
17647
17648    private static boolean isSystemApp(PackageSetting ps) {
17649        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17650    }
17651
17652    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17653        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17654    }
17655
17656    private int packageFlagsToInstallFlags(PackageSetting ps) {
17657        int installFlags = 0;
17658        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17659            // This existing package was an external ASEC install when we have
17660            // the external flag without a UUID
17661            installFlags |= PackageManager.INSTALL_EXTERNAL;
17662        }
17663        if (ps.isForwardLocked()) {
17664            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17665        }
17666        return installFlags;
17667    }
17668
17669    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17670        if (isExternal(pkg)) {
17671            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17672                return mSettings.getExternalVersion();
17673            } else {
17674                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17675            }
17676        } else {
17677            return mSettings.getInternalVersion();
17678        }
17679    }
17680
17681    private void deleteTempPackageFiles() {
17682        final FilenameFilter filter = new FilenameFilter() {
17683            public boolean accept(File dir, String name) {
17684                return name.startsWith("vmdl") && name.endsWith(".tmp");
17685            }
17686        };
17687        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17688            file.delete();
17689        }
17690    }
17691
17692    @Override
17693    public void deletePackageAsUser(String packageName, int versionCode,
17694            IPackageDeleteObserver observer, int userId, int flags) {
17695        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17696                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17697    }
17698
17699    @Override
17700    public void deletePackageVersioned(VersionedPackage versionedPackage,
17701            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17702        final int callingUid = Binder.getCallingUid();
17703        mContext.enforceCallingOrSelfPermission(
17704                android.Manifest.permission.DELETE_PACKAGES, null);
17705        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17706        Preconditions.checkNotNull(versionedPackage);
17707        Preconditions.checkNotNull(observer);
17708        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17709                PackageManager.VERSION_CODE_HIGHEST,
17710                Long.MAX_VALUE, "versionCode must be >= -1");
17711
17712        final String packageName = versionedPackage.getPackageName();
17713        final long versionCode = versionedPackage.getLongVersionCode();
17714        final String internalPackageName;
17715        synchronized (mPackages) {
17716            // Normalize package name to handle renamed packages and static libs
17717            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17718        }
17719
17720        final int uid = Binder.getCallingUid();
17721        if (!isOrphaned(internalPackageName)
17722                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17723            try {
17724                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17725                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17726                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17727                observer.onUserActionRequired(intent);
17728            } catch (RemoteException re) {
17729            }
17730            return;
17731        }
17732        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17733        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17734        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17735            mContext.enforceCallingOrSelfPermission(
17736                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17737                    "deletePackage for user " + userId);
17738        }
17739
17740        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17741            try {
17742                observer.onPackageDeleted(packageName,
17743                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17744            } catch (RemoteException re) {
17745            }
17746            return;
17747        }
17748
17749        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17750            try {
17751                observer.onPackageDeleted(packageName,
17752                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17753            } catch (RemoteException re) {
17754            }
17755            return;
17756        }
17757
17758        if (DEBUG_REMOVE) {
17759            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17760                    + " deleteAllUsers: " + deleteAllUsers + " version="
17761                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17762                    ? "VERSION_CODE_HIGHEST" : versionCode));
17763        }
17764        // Queue up an async operation since the package deletion may take a little while.
17765        mHandler.post(new Runnable() {
17766            public void run() {
17767                mHandler.removeCallbacks(this);
17768                int returnCode;
17769                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17770                boolean doDeletePackage = true;
17771                if (ps != null) {
17772                    final boolean targetIsInstantApp =
17773                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17774                    doDeletePackage = !targetIsInstantApp
17775                            || canViewInstantApps;
17776                }
17777                if (doDeletePackage) {
17778                    if (!deleteAllUsers) {
17779                        returnCode = deletePackageX(internalPackageName, versionCode,
17780                                userId, deleteFlags);
17781                    } else {
17782                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17783                                internalPackageName, users);
17784                        // If nobody is blocking uninstall, proceed with delete for all users
17785                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17786                            returnCode = deletePackageX(internalPackageName, versionCode,
17787                                    userId, deleteFlags);
17788                        } else {
17789                            // Otherwise uninstall individually for users with blockUninstalls=false
17790                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17791                            for (int userId : users) {
17792                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17793                                    returnCode = deletePackageX(internalPackageName, versionCode,
17794                                            userId, userFlags);
17795                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17796                                        Slog.w(TAG, "Package delete failed for user " + userId
17797                                                + ", returnCode " + returnCode);
17798                                    }
17799                                }
17800                            }
17801                            // The app has only been marked uninstalled for certain users.
17802                            // We still need to report that delete was blocked
17803                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17804                        }
17805                    }
17806                } else {
17807                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17808                }
17809                try {
17810                    observer.onPackageDeleted(packageName, returnCode, null);
17811                } catch (RemoteException e) {
17812                    Log.i(TAG, "Observer no longer exists.");
17813                } //end catch
17814            } //end run
17815        });
17816    }
17817
17818    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17819        if (pkg.staticSharedLibName != null) {
17820            return pkg.manifestPackageName;
17821        }
17822        return pkg.packageName;
17823    }
17824
17825    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17826        // Handle renamed packages
17827        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17828        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17829
17830        // Is this a static library?
17831        LongSparseArray<SharedLibraryEntry> versionedLib =
17832                mStaticLibsByDeclaringPackage.get(packageName);
17833        if (versionedLib == null || versionedLib.size() <= 0) {
17834            return packageName;
17835        }
17836
17837        // Figure out which lib versions the caller can see
17838        LongSparseLongArray versionsCallerCanSee = null;
17839        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17840        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17841                && callingAppId != Process.ROOT_UID) {
17842            versionsCallerCanSee = new LongSparseLongArray();
17843            String libName = versionedLib.valueAt(0).info.getName();
17844            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17845            if (uidPackages != null) {
17846                for (String uidPackage : uidPackages) {
17847                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17848                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17849                    if (libIdx >= 0) {
17850                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17851                        versionsCallerCanSee.append(libVersion, libVersion);
17852                    }
17853                }
17854            }
17855        }
17856
17857        // Caller can see nothing - done
17858        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17859            return packageName;
17860        }
17861
17862        // Find the version the caller can see and the app version code
17863        SharedLibraryEntry highestVersion = null;
17864        final int versionCount = versionedLib.size();
17865        for (int i = 0; i < versionCount; i++) {
17866            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17867            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17868                    libEntry.info.getLongVersion()) < 0) {
17869                continue;
17870            }
17871            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17872            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17873                if (libVersionCode == versionCode) {
17874                    return libEntry.apk;
17875                }
17876            } else if (highestVersion == null) {
17877                highestVersion = libEntry;
17878            } else if (libVersionCode  > highestVersion.info
17879                    .getDeclaringPackage().getLongVersionCode()) {
17880                highestVersion = libEntry;
17881            }
17882        }
17883
17884        if (highestVersion != null) {
17885            return highestVersion.apk;
17886        }
17887
17888        return packageName;
17889    }
17890
17891    boolean isCallerVerifier(int callingUid) {
17892        final int callingUserId = UserHandle.getUserId(callingUid);
17893        return mRequiredVerifierPackage != null &&
17894                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17895    }
17896
17897    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17898        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17899              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17900            return true;
17901        }
17902        final int callingUserId = UserHandle.getUserId(callingUid);
17903        // If the caller installed the pkgName, then allow it to silently uninstall.
17904        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17905            return true;
17906        }
17907
17908        // Allow package verifier to silently uninstall.
17909        if (mRequiredVerifierPackage != null &&
17910                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17911            return true;
17912        }
17913
17914        // Allow package uninstaller to silently uninstall.
17915        if (mRequiredUninstallerPackage != null &&
17916                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17917            return true;
17918        }
17919
17920        // Allow storage manager to silently uninstall.
17921        if (mStorageManagerPackage != null &&
17922                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17923            return true;
17924        }
17925
17926        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17927        // uninstall for device owner provisioning.
17928        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17929                == PERMISSION_GRANTED) {
17930            return true;
17931        }
17932
17933        return false;
17934    }
17935
17936    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17937        int[] result = EMPTY_INT_ARRAY;
17938        for (int userId : userIds) {
17939            if (getBlockUninstallForUser(packageName, userId)) {
17940                result = ArrayUtils.appendInt(result, userId);
17941            }
17942        }
17943        return result;
17944    }
17945
17946    @Override
17947    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17948        final int callingUid = Binder.getCallingUid();
17949        if (getInstantAppPackageName(callingUid) != null
17950                && !isCallerSameApp(packageName, callingUid)) {
17951            return false;
17952        }
17953        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17954    }
17955
17956    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17957        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17958                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17959        try {
17960            if (dpm != null) {
17961                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17962                        /* callingUserOnly =*/ false);
17963                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17964                        : deviceOwnerComponentName.getPackageName();
17965                // Does the package contains the device owner?
17966                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17967                // this check is probably not needed, since DO should be registered as a device
17968                // admin on some user too. (Original bug for this: b/17657954)
17969                if (packageName.equals(deviceOwnerPackageName)) {
17970                    return true;
17971                }
17972                // Does it contain a device admin for any user?
17973                int[] users;
17974                if (userId == UserHandle.USER_ALL) {
17975                    users = sUserManager.getUserIds();
17976                } else {
17977                    users = new int[]{userId};
17978                }
17979                for (int i = 0; i < users.length; ++i) {
17980                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17981                        return true;
17982                    }
17983                }
17984            }
17985        } catch (RemoteException e) {
17986        }
17987        return false;
17988    }
17989
17990    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17991        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17992    }
17993
17994    /**
17995     *  This method is an internal method that could be get invoked either
17996     *  to delete an installed package or to clean up a failed installation.
17997     *  After deleting an installed package, a broadcast is sent to notify any
17998     *  listeners that the package has been removed. For cleaning up a failed
17999     *  installation, the broadcast is not necessary since the package's
18000     *  installation wouldn't have sent the initial broadcast either
18001     *  The key steps in deleting a package are
18002     *  deleting the package information in internal structures like mPackages,
18003     *  deleting the packages base directories through installd
18004     *  updating mSettings to reflect current status
18005     *  persisting settings for later use
18006     *  sending a broadcast if necessary
18007     */
18008    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18009        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18010        final boolean res;
18011
18012        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18013                ? UserHandle.USER_ALL : userId;
18014
18015        if (isPackageDeviceAdmin(packageName, removeUser)) {
18016            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18017            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18018        }
18019
18020        PackageSetting uninstalledPs = null;
18021        PackageParser.Package pkg = null;
18022
18023        // for the uninstall-updates case and restricted profiles, remember the per-
18024        // user handle installed state
18025        int[] allUsers;
18026        synchronized (mPackages) {
18027            uninstalledPs = mSettings.mPackages.get(packageName);
18028            if (uninstalledPs == null) {
18029                Slog.w(TAG, "Not removing non-existent package " + packageName);
18030                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18031            }
18032
18033            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18034                    && uninstalledPs.versionCode != versionCode) {
18035                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18036                        + uninstalledPs.versionCode + " != " + versionCode);
18037                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18038            }
18039
18040            // Static shared libs can be declared by any package, so let us not
18041            // allow removing a package if it provides a lib others depend on.
18042            pkg = mPackages.get(packageName);
18043
18044            allUsers = sUserManager.getUserIds();
18045
18046            if (pkg != null && pkg.staticSharedLibName != null) {
18047                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18048                        pkg.staticSharedLibVersion);
18049                if (libEntry != null) {
18050                    for (int currUserId : allUsers) {
18051                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18052                            continue;
18053                        }
18054                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18055                                libEntry.info, 0, currUserId);
18056                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18057                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18058                                    + " hosting lib " + libEntry.info.getName() + " version "
18059                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18060                                    + " for user " + currUserId);
18061                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18062                        }
18063                    }
18064                }
18065            }
18066
18067            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18068        }
18069
18070        final int freezeUser;
18071        if (isUpdatedSystemApp(uninstalledPs)
18072                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18073            // We're downgrading a system app, which will apply to all users, so
18074            // freeze them all during the downgrade
18075            freezeUser = UserHandle.USER_ALL;
18076        } else {
18077            freezeUser = removeUser;
18078        }
18079
18080        synchronized (mInstallLock) {
18081            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18082            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18083                    deleteFlags, "deletePackageX")) {
18084                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18085                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18086            }
18087            synchronized (mPackages) {
18088                if (res) {
18089                    if (pkg != null) {
18090                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18091                    }
18092                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18093                    updateInstantAppInstallerLocked(packageName);
18094                }
18095            }
18096        }
18097
18098        if (res) {
18099            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18100            info.sendPackageRemovedBroadcasts(killApp);
18101            info.sendSystemPackageUpdatedBroadcasts();
18102            info.sendSystemPackageAppearedBroadcasts();
18103        }
18104        // Force a gc here.
18105        Runtime.getRuntime().gc();
18106        // Delete the resources here after sending the broadcast to let
18107        // other processes clean up before deleting resources.
18108        if (info.args != null) {
18109            synchronized (mInstallLock) {
18110                info.args.doPostDeleteLI(true);
18111            }
18112        }
18113
18114        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18115    }
18116
18117    static class PackageRemovedInfo {
18118        final PackageSender packageSender;
18119        String removedPackage;
18120        String installerPackageName;
18121        int uid = -1;
18122        int removedAppId = -1;
18123        int[] origUsers;
18124        int[] removedUsers = null;
18125        int[] broadcastUsers = null;
18126        int[] instantUserIds = null;
18127        SparseArray<Integer> installReasons;
18128        boolean isRemovedPackageSystemUpdate = false;
18129        boolean isUpdate;
18130        boolean dataRemoved;
18131        boolean removedForAllUsers;
18132        boolean isStaticSharedLib;
18133        // Clean up resources deleted packages.
18134        InstallArgs args = null;
18135        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18136        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18137
18138        PackageRemovedInfo(PackageSender packageSender) {
18139            this.packageSender = packageSender;
18140        }
18141
18142        void sendPackageRemovedBroadcasts(boolean killApp) {
18143            sendPackageRemovedBroadcastInternal(killApp);
18144            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18145            for (int i = 0; i < childCount; i++) {
18146                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18147                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18148            }
18149        }
18150
18151        void sendSystemPackageUpdatedBroadcasts() {
18152            if (isRemovedPackageSystemUpdate) {
18153                sendSystemPackageUpdatedBroadcastsInternal();
18154                final int childCount = (removedChildPackages != null)
18155                        ? removedChildPackages.size() : 0;
18156                for (int i = 0; i < childCount; i++) {
18157                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18158                    if (childInfo.isRemovedPackageSystemUpdate) {
18159                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18160                    }
18161                }
18162            }
18163        }
18164
18165        void sendSystemPackageAppearedBroadcasts() {
18166            final int packageCount = (appearedChildPackages != null)
18167                    ? appearedChildPackages.size() : 0;
18168            for (int i = 0; i < packageCount; i++) {
18169                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18170                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18171                    true /*sendBootCompleted*/, false /*startReceiver*/,
18172                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18173            }
18174        }
18175
18176        private void sendSystemPackageUpdatedBroadcastsInternal() {
18177            Bundle extras = new Bundle(2);
18178            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18179            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18180            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18181                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18182            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18183                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18184            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18185                null, null, 0, removedPackage, null, null, null);
18186            if (installerPackageName != null) {
18187                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18188                        removedPackage, extras, 0 /*flags*/,
18189                        installerPackageName, null, null, null);
18190                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18191                        removedPackage, extras, 0 /*flags*/,
18192                        installerPackageName, null, null, null);
18193            }
18194        }
18195
18196        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18197            // Don't send static shared library removal broadcasts as these
18198            // libs are visible only the the apps that depend on them an one
18199            // cannot remove the library if it has a dependency.
18200            if (isStaticSharedLib) {
18201                return;
18202            }
18203            Bundle extras = new Bundle(2);
18204            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18205            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18206            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18207            if (isUpdate || isRemovedPackageSystemUpdate) {
18208                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18209            }
18210            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18211            if (removedPackage != null) {
18212                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18213                    removedPackage, extras, 0, null /*targetPackage*/, null,
18214                    broadcastUsers, instantUserIds);
18215                if (installerPackageName != null) {
18216                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18217                            removedPackage, extras, 0 /*flags*/,
18218                            installerPackageName, null, broadcastUsers, instantUserIds);
18219                }
18220                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18221                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18222                        removedPackage, extras,
18223                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18224                        null, null, broadcastUsers, instantUserIds);
18225                    packageSender.notifyPackageRemoved(removedPackage);
18226                }
18227            }
18228            if (removedAppId >= 0) {
18229                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18230                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18231                    null, null, broadcastUsers, instantUserIds);
18232            }
18233        }
18234
18235        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18236            removedUsers = userIds;
18237            if (removedUsers == null) {
18238                broadcastUsers = null;
18239                return;
18240            }
18241
18242            broadcastUsers = EMPTY_INT_ARRAY;
18243            instantUserIds = EMPTY_INT_ARRAY;
18244            for (int i = userIds.length - 1; i >= 0; --i) {
18245                final int userId = userIds[i];
18246                if (deletedPackageSetting.getInstantApp(userId)) {
18247                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18248                } else {
18249                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18250                }
18251            }
18252        }
18253    }
18254
18255    /*
18256     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18257     * flag is not set, the data directory is removed as well.
18258     * make sure this flag is set for partially installed apps. If not its meaningless to
18259     * delete a partially installed application.
18260     */
18261    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18262            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18263        String packageName = ps.name;
18264        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18265        // Retrieve object to delete permissions for shared user later on
18266        final PackageParser.Package deletedPkg;
18267        final PackageSetting deletedPs;
18268        // reader
18269        synchronized (mPackages) {
18270            deletedPkg = mPackages.get(packageName);
18271            deletedPs = mSettings.mPackages.get(packageName);
18272            if (outInfo != null) {
18273                outInfo.removedPackage = packageName;
18274                outInfo.installerPackageName = ps.installerPackageName;
18275                outInfo.isStaticSharedLib = deletedPkg != null
18276                        && deletedPkg.staticSharedLibName != null;
18277                outInfo.populateUsers(deletedPs == null ? null
18278                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18279            }
18280        }
18281
18282        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18283
18284        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18285            final PackageParser.Package resolvedPkg;
18286            if (deletedPkg != null) {
18287                resolvedPkg = deletedPkg;
18288            } else {
18289                // We don't have a parsed package when it lives on an ejected
18290                // adopted storage device, so fake something together
18291                resolvedPkg = new PackageParser.Package(ps.name);
18292                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18293            }
18294            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18295                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18296            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18297            if (outInfo != null) {
18298                outInfo.dataRemoved = true;
18299            }
18300            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18301        }
18302
18303        int removedAppId = -1;
18304
18305        // writer
18306        synchronized (mPackages) {
18307            boolean installedStateChanged = false;
18308            if (deletedPs != null) {
18309                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18310                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18311                    clearDefaultBrowserIfNeeded(packageName);
18312                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18313                    removedAppId = mSettings.removePackageLPw(packageName);
18314                    if (outInfo != null) {
18315                        outInfo.removedAppId = removedAppId;
18316                    }
18317                    mPermissionManager.updatePermissions(
18318                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18319                    if (deletedPs.sharedUser != null) {
18320                        // Remove permissions associated with package. Since runtime
18321                        // permissions are per user we have to kill the removed package
18322                        // or packages running under the shared user of the removed
18323                        // package if revoking the permissions requested only by the removed
18324                        // package is successful and this causes a change in gids.
18325                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18326                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18327                                    userId);
18328                            if (userIdToKill == UserHandle.USER_ALL
18329                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18330                                // If gids changed for this user, kill all affected packages.
18331                                mHandler.post(new Runnable() {
18332                                    @Override
18333                                    public void run() {
18334                                        // This has to happen with no lock held.
18335                                        killApplication(deletedPs.name, deletedPs.appId,
18336                                                KILL_APP_REASON_GIDS_CHANGED);
18337                                    }
18338                                });
18339                                break;
18340                            }
18341                        }
18342                    }
18343                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18344                }
18345                // make sure to preserve per-user disabled state if this removal was just
18346                // a downgrade of a system app to the factory package
18347                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18348                    if (DEBUG_REMOVE) {
18349                        Slog.d(TAG, "Propagating install state across downgrade");
18350                    }
18351                    for (int userId : allUserHandles) {
18352                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18353                        if (DEBUG_REMOVE) {
18354                            Slog.d(TAG, "    user " + userId + " => " + installed);
18355                        }
18356                        if (installed != ps.getInstalled(userId)) {
18357                            installedStateChanged = true;
18358                        }
18359                        ps.setInstalled(installed, userId);
18360                    }
18361                }
18362            }
18363            // can downgrade to reader
18364            if (writeSettings) {
18365                // Save settings now
18366                mSettings.writeLPr();
18367            }
18368            if (installedStateChanged) {
18369                mSettings.writeKernelMappingLPr(ps);
18370            }
18371        }
18372        if (removedAppId != -1) {
18373            // A user ID was deleted here. Go through all users and remove it
18374            // from KeyStore.
18375            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18376        }
18377    }
18378
18379    static boolean locationIsPrivileged(String path) {
18380        try {
18381            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18382            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18383            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18384            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18385            return path.startsWith(privilegedAppDir.getCanonicalPath())
18386                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18387                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18388                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18389        } catch (IOException e) {
18390            Slog.e(TAG, "Unable to access code path " + path);
18391        }
18392        return false;
18393    }
18394
18395    static boolean locationIsOem(String path) {
18396        try {
18397            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18398        } catch (IOException e) {
18399            Slog.e(TAG, "Unable to access code path " + path);
18400        }
18401        return false;
18402    }
18403
18404    static boolean locationIsVendor(String path) {
18405        try {
18406            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18407                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18408        } catch (IOException e) {
18409            Slog.e(TAG, "Unable to access code path " + path);
18410        }
18411        return false;
18412    }
18413
18414    static boolean locationIsProduct(String path) {
18415        try {
18416            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18417        } catch (IOException e) {
18418            Slog.e(TAG, "Unable to access code path " + path);
18419        }
18420        return false;
18421    }
18422
18423    /*
18424     * Tries to delete system package.
18425     */
18426    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18427            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18428            boolean writeSettings) {
18429        if (deletedPs.parentPackageName != null) {
18430            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18431            return false;
18432        }
18433
18434        final boolean applyUserRestrictions
18435                = (allUserHandles != null) && (outInfo.origUsers != null);
18436        final PackageSetting disabledPs;
18437        // Confirm if the system package has been updated
18438        // An updated system app can be deleted. This will also have to restore
18439        // the system pkg from system partition
18440        // reader
18441        synchronized (mPackages) {
18442            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18443        }
18444
18445        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18446                + " disabledPs=" + disabledPs);
18447
18448        if (disabledPs == null) {
18449            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18450            return false;
18451        } else if (DEBUG_REMOVE) {
18452            Slog.d(TAG, "Deleting system pkg from data partition");
18453        }
18454
18455        if (DEBUG_REMOVE) {
18456            if (applyUserRestrictions) {
18457                Slog.d(TAG, "Remembering install states:");
18458                for (int userId : allUserHandles) {
18459                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18460                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18461                }
18462            }
18463        }
18464
18465        // Delete the updated package
18466        outInfo.isRemovedPackageSystemUpdate = true;
18467        if (outInfo.removedChildPackages != null) {
18468            final int childCount = (deletedPs.childPackageNames != null)
18469                    ? deletedPs.childPackageNames.size() : 0;
18470            for (int i = 0; i < childCount; i++) {
18471                String childPackageName = deletedPs.childPackageNames.get(i);
18472                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18473                        .contains(childPackageName)) {
18474                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18475                            childPackageName);
18476                    if (childInfo != null) {
18477                        childInfo.isRemovedPackageSystemUpdate = true;
18478                    }
18479                }
18480            }
18481        }
18482
18483        if (disabledPs.versionCode < deletedPs.versionCode) {
18484            // Delete data for downgrades
18485            flags &= ~PackageManager.DELETE_KEEP_DATA;
18486        } else {
18487            // Preserve data by setting flag
18488            flags |= PackageManager.DELETE_KEEP_DATA;
18489        }
18490
18491        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18492                outInfo, writeSettings, disabledPs.pkg);
18493        if (!ret) {
18494            return false;
18495        }
18496
18497        // writer
18498        synchronized (mPackages) {
18499            // NOTE: The system package always needs to be enabled; even if it's for
18500            // a compressed stub. If we don't, installing the system package fails
18501            // during scan [scanning checks the disabled packages]. We will reverse
18502            // this later, after we've "installed" the stub.
18503            // Reinstate the old system package
18504            enableSystemPackageLPw(disabledPs.pkg);
18505            // Remove any native libraries from the upgraded package.
18506            removeNativeBinariesLI(deletedPs);
18507        }
18508
18509        // Install the system package
18510        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18511        try {
18512            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18513                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18514        } catch (PackageManagerException e) {
18515            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18516                    + e.getMessage());
18517            return false;
18518        } finally {
18519            if (disabledPs.pkg.isStub) {
18520                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18521            }
18522        }
18523        return true;
18524    }
18525
18526    /**
18527     * Installs a package that's already on the system partition.
18528     */
18529    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18530            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18531            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18532                    throws PackageManagerException {
18533        @ParseFlags int parseFlags =
18534                mDefParseFlags
18535                | PackageParser.PARSE_MUST_BE_APK
18536                | PackageParser.PARSE_IS_SYSTEM_DIR;
18537        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18538        if (isPrivileged || locationIsPrivileged(codePathString)) {
18539            scanFlags |= SCAN_AS_PRIVILEGED;
18540        }
18541        if (locationIsOem(codePathString)) {
18542            scanFlags |= SCAN_AS_OEM;
18543        }
18544        if (locationIsVendor(codePathString)) {
18545            scanFlags |= SCAN_AS_VENDOR;
18546        }
18547        if (locationIsProduct(codePathString)) {
18548            scanFlags |= SCAN_AS_PRODUCT;
18549        }
18550
18551        final File codePath = new File(codePathString);
18552        final PackageParser.Package pkg =
18553                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18554
18555        try {
18556            // update shared libraries for the newly re-installed system package
18557            updateSharedLibrariesLPr(pkg, null);
18558        } catch (PackageManagerException e) {
18559            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18560        }
18561
18562        prepareAppDataAfterInstallLIF(pkg);
18563
18564        // writer
18565        synchronized (mPackages) {
18566            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18567
18568            // Propagate the permissions state as we do not want to drop on the floor
18569            // runtime permissions. The update permissions method below will take
18570            // care of removing obsolete permissions and grant install permissions.
18571            if (origPermissionState != null) {
18572                ps.getPermissionsState().copyFrom(origPermissionState);
18573            }
18574            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18575                    mPermissionCallback);
18576
18577            final boolean applyUserRestrictions
18578                    = (allUserHandles != null) && (origUserHandles != null);
18579            if (applyUserRestrictions) {
18580                boolean installedStateChanged = false;
18581                if (DEBUG_REMOVE) {
18582                    Slog.d(TAG, "Propagating install state across reinstall");
18583                }
18584                for (int userId : allUserHandles) {
18585                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18586                    if (DEBUG_REMOVE) {
18587                        Slog.d(TAG, "    user " + userId + " => " + installed);
18588                    }
18589                    if (installed != ps.getInstalled(userId)) {
18590                        installedStateChanged = true;
18591                    }
18592                    ps.setInstalled(installed, userId);
18593
18594                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18595                }
18596                // Regardless of writeSettings we need to ensure that this restriction
18597                // state propagation is persisted
18598                mSettings.writeAllUsersPackageRestrictionsLPr();
18599                if (installedStateChanged) {
18600                    mSettings.writeKernelMappingLPr(ps);
18601                }
18602            }
18603            // can downgrade to reader here
18604            if (writeSettings) {
18605                mSettings.writeLPr();
18606            }
18607        }
18608        return pkg;
18609    }
18610
18611    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18612            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18613            PackageRemovedInfo outInfo, boolean writeSettings,
18614            PackageParser.Package replacingPackage) {
18615        synchronized (mPackages) {
18616            if (outInfo != null) {
18617                outInfo.uid = ps.appId;
18618            }
18619
18620            if (outInfo != null && outInfo.removedChildPackages != null) {
18621                final int childCount = (ps.childPackageNames != null)
18622                        ? ps.childPackageNames.size() : 0;
18623                for (int i = 0; i < childCount; i++) {
18624                    String childPackageName = ps.childPackageNames.get(i);
18625                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18626                    if (childPs == null) {
18627                        return false;
18628                    }
18629                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18630                            childPackageName);
18631                    if (childInfo != null) {
18632                        childInfo.uid = childPs.appId;
18633                    }
18634                }
18635            }
18636        }
18637
18638        // Delete package data from internal structures and also remove data if flag is set
18639        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18640
18641        // Delete the child packages data
18642        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18643        for (int i = 0; i < childCount; i++) {
18644            PackageSetting childPs;
18645            synchronized (mPackages) {
18646                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18647            }
18648            if (childPs != null) {
18649                PackageRemovedInfo childOutInfo = (outInfo != null
18650                        && outInfo.removedChildPackages != null)
18651                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18652                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18653                        && (replacingPackage != null
18654                        && !replacingPackage.hasChildPackage(childPs.name))
18655                        ? flags & ~DELETE_KEEP_DATA : flags;
18656                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18657                        deleteFlags, writeSettings);
18658            }
18659        }
18660
18661        // Delete application code and resources only for parent packages
18662        if (ps.parentPackageName == null) {
18663            if (deleteCodeAndResources && (outInfo != null)) {
18664                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18665                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18666                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18667            }
18668        }
18669
18670        return true;
18671    }
18672
18673    @Override
18674    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18675            int userId) {
18676        mContext.enforceCallingOrSelfPermission(
18677                android.Manifest.permission.DELETE_PACKAGES, null);
18678        synchronized (mPackages) {
18679            // Cannot block uninstall of static shared libs as they are
18680            // considered a part of the using app (emulating static linking).
18681            // Also static libs are installed always on internal storage.
18682            PackageParser.Package pkg = mPackages.get(packageName);
18683            if (pkg != null && pkg.staticSharedLibName != null) {
18684                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18685                        + " providing static shared library: " + pkg.staticSharedLibName);
18686                return false;
18687            }
18688            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18689            mSettings.writePackageRestrictionsLPr(userId);
18690        }
18691        return true;
18692    }
18693
18694    @Override
18695    public boolean getBlockUninstallForUser(String packageName, int userId) {
18696        synchronized (mPackages) {
18697            final PackageSetting ps = mSettings.mPackages.get(packageName);
18698            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18699                return false;
18700            }
18701            return mSettings.getBlockUninstallLPr(userId, packageName);
18702        }
18703    }
18704
18705    @Override
18706    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18707        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18708        synchronized (mPackages) {
18709            PackageSetting ps = mSettings.mPackages.get(packageName);
18710            if (ps == null) {
18711                Log.w(TAG, "Package doesn't exist: " + packageName);
18712                return false;
18713            }
18714            if (systemUserApp) {
18715                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18716            } else {
18717                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18718            }
18719            mSettings.writeLPr();
18720        }
18721        return true;
18722    }
18723
18724    /*
18725     * This method handles package deletion in general
18726     */
18727    private boolean deletePackageLIF(String packageName, UserHandle user,
18728            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18729            PackageRemovedInfo outInfo, boolean writeSettings,
18730            PackageParser.Package replacingPackage) {
18731        if (packageName == null) {
18732            Slog.w(TAG, "Attempt to delete null packageName.");
18733            return false;
18734        }
18735
18736        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18737
18738        PackageSetting ps;
18739        synchronized (mPackages) {
18740            ps = mSettings.mPackages.get(packageName);
18741            if (ps == null) {
18742                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18743                return false;
18744            }
18745
18746            if (ps.parentPackageName != null && (!isSystemApp(ps)
18747                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18748                if (DEBUG_REMOVE) {
18749                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18750                            + ((user == null) ? UserHandle.USER_ALL : user));
18751                }
18752                final int removedUserId = (user != null) ? user.getIdentifier()
18753                        : UserHandle.USER_ALL;
18754
18755                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18756                    return false;
18757                }
18758                markPackageUninstalledForUserLPw(ps, user);
18759                scheduleWritePackageRestrictionsLocked(user);
18760                return true;
18761            }
18762        }
18763
18764        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18765        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18766            onSuspendingPackageRemoved(packageName, userId);
18767        }
18768
18769
18770        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18771                && user.getIdentifier() != UserHandle.USER_ALL)) {
18772            // The caller is asking that the package only be deleted for a single
18773            // user.  To do this, we just mark its uninstalled state and delete
18774            // its data. If this is a system app, we only allow this to happen if
18775            // they have set the special DELETE_SYSTEM_APP which requests different
18776            // semantics than normal for uninstalling system apps.
18777            markPackageUninstalledForUserLPw(ps, user);
18778
18779            if (!isSystemApp(ps)) {
18780                // Do not uninstall the APK if an app should be cached
18781                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18782                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18783                    // Other user still have this package installed, so all
18784                    // we need to do is clear this user's data and save that
18785                    // it is uninstalled.
18786                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18787                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18788                        return false;
18789                    }
18790                    scheduleWritePackageRestrictionsLocked(user);
18791                    return true;
18792                } else {
18793                    // We need to set it back to 'installed' so the uninstall
18794                    // broadcasts will be sent correctly.
18795                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18796                    ps.setInstalled(true, user.getIdentifier());
18797                    mSettings.writeKernelMappingLPr(ps);
18798                }
18799            } else {
18800                // This is a system app, so we assume that the
18801                // other users still have this package installed, so all
18802                // we need to do is clear this user's data and save that
18803                // it is uninstalled.
18804                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18805                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18806                    return false;
18807                }
18808                scheduleWritePackageRestrictionsLocked(user);
18809                return true;
18810            }
18811        }
18812
18813        // If we are deleting a composite package for all users, keep track
18814        // of result for each child.
18815        if (ps.childPackageNames != null && outInfo != null) {
18816            synchronized (mPackages) {
18817                final int childCount = ps.childPackageNames.size();
18818                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18819                for (int i = 0; i < childCount; i++) {
18820                    String childPackageName = ps.childPackageNames.get(i);
18821                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18822                    childInfo.removedPackage = childPackageName;
18823                    childInfo.installerPackageName = ps.installerPackageName;
18824                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18825                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18826                    if (childPs != null) {
18827                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18828                    }
18829                }
18830            }
18831        }
18832
18833        boolean ret = false;
18834        if (isSystemApp(ps)) {
18835            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18836            // When an updated system application is deleted we delete the existing resources
18837            // as well and fall back to existing code in system partition
18838            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18839        } else {
18840            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18841            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18842                    outInfo, writeSettings, replacingPackage);
18843        }
18844
18845        // Take a note whether we deleted the package for all users
18846        if (outInfo != null) {
18847            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18848            if (outInfo.removedChildPackages != null) {
18849                synchronized (mPackages) {
18850                    final int childCount = outInfo.removedChildPackages.size();
18851                    for (int i = 0; i < childCount; i++) {
18852                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18853                        if (childInfo != null) {
18854                            childInfo.removedForAllUsers = mPackages.get(
18855                                    childInfo.removedPackage) == null;
18856                        }
18857                    }
18858                }
18859            }
18860            // If we uninstalled an update to a system app there may be some
18861            // child packages that appeared as they are declared in the system
18862            // app but were not declared in the update.
18863            if (isSystemApp(ps)) {
18864                synchronized (mPackages) {
18865                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18866                    final int childCount = (updatedPs.childPackageNames != null)
18867                            ? updatedPs.childPackageNames.size() : 0;
18868                    for (int i = 0; i < childCount; i++) {
18869                        String childPackageName = updatedPs.childPackageNames.get(i);
18870                        if (outInfo.removedChildPackages == null
18871                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18872                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18873                            if (childPs == null) {
18874                                continue;
18875                            }
18876                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18877                            installRes.name = childPackageName;
18878                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18879                            installRes.pkg = mPackages.get(childPackageName);
18880                            installRes.uid = childPs.pkg.applicationInfo.uid;
18881                            if (outInfo.appearedChildPackages == null) {
18882                                outInfo.appearedChildPackages = new ArrayMap<>();
18883                            }
18884                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18885                        }
18886                    }
18887                }
18888            }
18889        }
18890
18891        return ret;
18892    }
18893
18894    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18895        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18896                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18897        for (int nextUserId : userIds) {
18898            if (DEBUG_REMOVE) {
18899                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18900            }
18901            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18902                    false /*installed*/,
18903                    true /*stopped*/,
18904                    true /*notLaunched*/,
18905                    false /*hidden*/,
18906                    false /*suspended*/,
18907                    null, /*suspendingPackage*/
18908                    null, /*dialogMessage*/
18909                    null, /*suspendedAppExtras*/
18910                    null, /*suspendedLauncherExtras*/
18911                    false /*instantApp*/,
18912                    false /*virtualPreload*/,
18913                    null /*lastDisableAppCaller*/,
18914                    null /*enabledComponents*/,
18915                    null /*disabledComponents*/,
18916                    ps.readUserState(nextUserId).domainVerificationStatus,
18917                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18918                    null /*harmfulAppWarning*/);
18919        }
18920        mSettings.writeKernelMappingLPr(ps);
18921    }
18922
18923    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18924            PackageRemovedInfo outInfo) {
18925        final PackageParser.Package pkg;
18926        synchronized (mPackages) {
18927            pkg = mPackages.get(ps.name);
18928        }
18929
18930        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18931                : new int[] {userId};
18932        for (int nextUserId : userIds) {
18933            if (DEBUG_REMOVE) {
18934                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18935                        + nextUserId);
18936            }
18937
18938            destroyAppDataLIF(pkg, userId,
18939                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18940            destroyAppProfilesLIF(pkg, userId);
18941            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18942            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18943            schedulePackageCleaning(ps.name, nextUserId, false);
18944            synchronized (mPackages) {
18945                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18946                    scheduleWritePackageRestrictionsLocked(nextUserId);
18947                }
18948                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18949            }
18950        }
18951
18952        if (outInfo != null) {
18953            outInfo.removedPackage = ps.name;
18954            outInfo.installerPackageName = ps.installerPackageName;
18955            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18956            outInfo.removedAppId = ps.appId;
18957            outInfo.removedUsers = userIds;
18958            outInfo.broadcastUsers = userIds;
18959        }
18960
18961        return true;
18962    }
18963
18964    private final class ClearStorageConnection implements ServiceConnection {
18965        IMediaContainerService mContainerService;
18966
18967        @Override
18968        public void onServiceConnected(ComponentName name, IBinder service) {
18969            synchronized (this) {
18970                mContainerService = IMediaContainerService.Stub
18971                        .asInterface(Binder.allowBlocking(service));
18972                notifyAll();
18973            }
18974        }
18975
18976        @Override
18977        public void onServiceDisconnected(ComponentName name) {
18978        }
18979    }
18980
18981    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18982        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18983
18984        final boolean mounted;
18985        if (Environment.isExternalStorageEmulated()) {
18986            mounted = true;
18987        } else {
18988            final String status = Environment.getExternalStorageState();
18989
18990            mounted = status.equals(Environment.MEDIA_MOUNTED)
18991                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18992        }
18993
18994        if (!mounted) {
18995            return;
18996        }
18997
18998        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18999        int[] users;
19000        if (userId == UserHandle.USER_ALL) {
19001            users = sUserManager.getUserIds();
19002        } else {
19003            users = new int[] { userId };
19004        }
19005        final ClearStorageConnection conn = new ClearStorageConnection();
19006        if (mContext.bindServiceAsUser(
19007                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19008            try {
19009                for (int curUser : users) {
19010                    long timeout = SystemClock.uptimeMillis() + 5000;
19011                    synchronized (conn) {
19012                        long now;
19013                        while (conn.mContainerService == null &&
19014                                (now = SystemClock.uptimeMillis()) < timeout) {
19015                            try {
19016                                conn.wait(timeout - now);
19017                            } catch (InterruptedException e) {
19018                            }
19019                        }
19020                    }
19021                    if (conn.mContainerService == null) {
19022                        return;
19023                    }
19024
19025                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19026                    clearDirectory(conn.mContainerService,
19027                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19028                    if (allData) {
19029                        clearDirectory(conn.mContainerService,
19030                                userEnv.buildExternalStorageAppDataDirs(packageName));
19031                        clearDirectory(conn.mContainerService,
19032                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19033                    }
19034                }
19035            } finally {
19036                mContext.unbindService(conn);
19037            }
19038        }
19039    }
19040
19041    @Override
19042    public void clearApplicationProfileData(String packageName) {
19043        enforceSystemOrRoot("Only the system can clear all profile data");
19044
19045        final PackageParser.Package pkg;
19046        synchronized (mPackages) {
19047            pkg = mPackages.get(packageName);
19048        }
19049
19050        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19051            synchronized (mInstallLock) {
19052                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19053            }
19054        }
19055    }
19056
19057    @Override
19058    public void clearApplicationUserData(final String packageName,
19059            final IPackageDataObserver observer, final int userId) {
19060        mContext.enforceCallingOrSelfPermission(
19061                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19062
19063        final int callingUid = Binder.getCallingUid();
19064        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19065                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19066
19067        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19068        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19069        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19070            throw new SecurityException("Cannot clear data for a protected package: "
19071                    + packageName);
19072        }
19073        // Queue up an async operation since the package deletion may take a little while.
19074        mHandler.post(new Runnable() {
19075            public void run() {
19076                mHandler.removeCallbacks(this);
19077                final boolean succeeded;
19078                if (!filterApp) {
19079                    try (PackageFreezer freezer = freezePackage(packageName,
19080                            "clearApplicationUserData")) {
19081                        synchronized (mInstallLock) {
19082                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19083                        }
19084                        clearExternalStorageDataSync(packageName, userId, true);
19085                        synchronized (mPackages) {
19086                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19087                                    packageName, userId);
19088                        }
19089                    }
19090                    if (succeeded) {
19091                        // invoke DeviceStorageMonitor's update method to clear any notifications
19092                        DeviceStorageMonitorInternal dsm = LocalServices
19093                                .getService(DeviceStorageMonitorInternal.class);
19094                        if (dsm != null) {
19095                            dsm.checkMemory();
19096                        }
19097                    }
19098                } else {
19099                    succeeded = false;
19100                }
19101                if (observer != null) {
19102                    try {
19103                        observer.onRemoveCompleted(packageName, succeeded);
19104                    } catch (RemoteException e) {
19105                        Log.i(TAG, "Observer no longer exists.");
19106                    }
19107                } //end if observer
19108            } //end run
19109        });
19110    }
19111
19112    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19113        if (packageName == null) {
19114            Slog.w(TAG, "Attempt to delete null packageName.");
19115            return false;
19116        }
19117
19118        // Try finding details about the requested package
19119        PackageParser.Package pkg;
19120        synchronized (mPackages) {
19121            pkg = mPackages.get(packageName);
19122            if (pkg == null) {
19123                final PackageSetting ps = mSettings.mPackages.get(packageName);
19124                if (ps != null) {
19125                    pkg = ps.pkg;
19126                }
19127            }
19128
19129            if (pkg == null) {
19130                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19131                return false;
19132            }
19133
19134            PackageSetting ps = (PackageSetting) pkg.mExtras;
19135            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19136        }
19137
19138        clearAppDataLIF(pkg, userId,
19139                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19140
19141        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19142        removeKeystoreDataIfNeeded(userId, appId);
19143
19144        UserManagerInternal umInternal = getUserManagerInternal();
19145        final int flags;
19146        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19147            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19148        } else if (umInternal.isUserRunning(userId)) {
19149            flags = StorageManager.FLAG_STORAGE_DE;
19150        } else {
19151            flags = 0;
19152        }
19153        prepareAppDataContentsLIF(pkg, userId, flags);
19154
19155        return true;
19156    }
19157
19158    /**
19159     * Reverts user permission state changes (permissions and flags) in
19160     * all packages for a given user.
19161     *
19162     * @param userId The device user for which to do a reset.
19163     */
19164    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19165        final int packageCount = mPackages.size();
19166        for (int i = 0; i < packageCount; i++) {
19167            PackageParser.Package pkg = mPackages.valueAt(i);
19168            PackageSetting ps = (PackageSetting) pkg.mExtras;
19169            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19170        }
19171    }
19172
19173    private void resetNetworkPolicies(int userId) {
19174        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19175    }
19176
19177    /**
19178     * Reverts user permission state changes (permissions and flags).
19179     *
19180     * @param ps The package for which to reset.
19181     * @param userId The device user for which to do a reset.
19182     */
19183    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19184            final PackageSetting ps, final int userId) {
19185        if (ps.pkg == null) {
19186            return;
19187        }
19188
19189        // These are flags that can change base on user actions.
19190        final int userSettableMask = FLAG_PERMISSION_USER_SET
19191                | FLAG_PERMISSION_USER_FIXED
19192                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19193                | FLAG_PERMISSION_REVIEW_REQUIRED;
19194
19195        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19196                | FLAG_PERMISSION_POLICY_FIXED;
19197
19198        boolean writeInstallPermissions = false;
19199        boolean writeRuntimePermissions = false;
19200
19201        final int permissionCount = ps.pkg.requestedPermissions.size();
19202        for (int i = 0; i < permissionCount; i++) {
19203            final String permName = ps.pkg.requestedPermissions.get(i);
19204            final BasePermission bp =
19205                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19206            if (bp == null) {
19207                continue;
19208            }
19209
19210            // If shared user we just reset the state to which only this app contributed.
19211            if (ps.sharedUser != null) {
19212                boolean used = false;
19213                final int packageCount = ps.sharedUser.packages.size();
19214                for (int j = 0; j < packageCount; j++) {
19215                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19216                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19217                            && pkg.pkg.requestedPermissions.contains(permName)) {
19218                        used = true;
19219                        break;
19220                    }
19221                }
19222                if (used) {
19223                    continue;
19224                }
19225            }
19226
19227            final PermissionsState permissionsState = ps.getPermissionsState();
19228
19229            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19230
19231            // Always clear the user settable flags.
19232            final boolean hasInstallState =
19233                    permissionsState.getInstallPermissionState(permName) != null;
19234            // If permission review is enabled and this is a legacy app, mark the
19235            // permission as requiring a review as this is the initial state.
19236            int flags = 0;
19237            if (mSettings.mPermissions.mPermissionReviewRequired
19238                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19239                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19240            }
19241            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19242                if (hasInstallState) {
19243                    writeInstallPermissions = true;
19244                } else {
19245                    writeRuntimePermissions = true;
19246                }
19247            }
19248
19249            // Below is only runtime permission handling.
19250            if (!bp.isRuntime()) {
19251                continue;
19252            }
19253
19254            // Never clobber system or policy.
19255            if ((oldFlags & policyOrSystemFlags) != 0) {
19256                continue;
19257            }
19258
19259            // If this permission was granted by default, make sure it is.
19260            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19261                if (permissionsState.grantRuntimePermission(bp, userId)
19262                        != PERMISSION_OPERATION_FAILURE) {
19263                    writeRuntimePermissions = true;
19264                }
19265            // If permission review is enabled the permissions for a legacy apps
19266            // are represented as constantly granted runtime ones, so don't revoke.
19267            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19268                // Otherwise, reset the permission.
19269                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19270                switch (revokeResult) {
19271                    case PERMISSION_OPERATION_SUCCESS:
19272                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19273                        writeRuntimePermissions = true;
19274                        final int appId = ps.appId;
19275                        mHandler.post(new Runnable() {
19276                            @Override
19277                            public void run() {
19278                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19279                            }
19280                        });
19281                    } break;
19282                }
19283            }
19284        }
19285
19286        // Synchronously write as we are taking permissions away.
19287        if (writeRuntimePermissions) {
19288            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19289        }
19290
19291        // Synchronously write as we are taking permissions away.
19292        if (writeInstallPermissions) {
19293            mSettings.writeLPr();
19294        }
19295    }
19296
19297    /**
19298     * Remove entries from the keystore daemon. Will only remove it if the
19299     * {@code appId} is valid.
19300     */
19301    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19302        if (appId < 0) {
19303            return;
19304        }
19305
19306        final KeyStore keyStore = KeyStore.getInstance();
19307        if (keyStore != null) {
19308            if (userId == UserHandle.USER_ALL) {
19309                for (final int individual : sUserManager.getUserIds()) {
19310                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19311                }
19312            } else {
19313                keyStore.clearUid(UserHandle.getUid(userId, appId));
19314            }
19315        } else {
19316            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19317        }
19318    }
19319
19320    @Override
19321    public void deleteApplicationCacheFiles(final String packageName,
19322            final IPackageDataObserver observer) {
19323        final int userId = UserHandle.getCallingUserId();
19324        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19325    }
19326
19327    @Override
19328    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19329            final IPackageDataObserver observer) {
19330        final int callingUid = Binder.getCallingUid();
19331        if (mContext.checkCallingOrSelfPermission(
19332                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19333                != PackageManager.PERMISSION_GRANTED) {
19334            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19335            if (mContext.checkCallingOrSelfPermission(
19336                    android.Manifest.permission.DELETE_CACHE_FILES)
19337                    == PackageManager.PERMISSION_GRANTED) {
19338                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19339                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19340                        ", silently ignoring");
19341                return;
19342            }
19343            mContext.enforceCallingOrSelfPermission(
19344                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19345        }
19346        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19347                /* requireFullPermission= */ true, /* checkShell= */ false,
19348                "delete application cache files");
19349        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19350                android.Manifest.permission.ACCESS_INSTANT_APPS);
19351
19352        final PackageParser.Package pkg;
19353        synchronized (mPackages) {
19354            pkg = mPackages.get(packageName);
19355        }
19356
19357        // Queue up an async operation since the package deletion may take a little while.
19358        mHandler.post(new Runnable() {
19359            public void run() {
19360                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19361                boolean doClearData = true;
19362                if (ps != null) {
19363                    final boolean targetIsInstantApp =
19364                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19365                    doClearData = !targetIsInstantApp
19366                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19367                }
19368                if (doClearData) {
19369                    synchronized (mInstallLock) {
19370                        final int flags = StorageManager.FLAG_STORAGE_DE
19371                                | StorageManager.FLAG_STORAGE_CE;
19372                        // We're only clearing cache files, so we don't care if the
19373                        // app is unfrozen and still able to run
19374                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19375                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19376                    }
19377                    clearExternalStorageDataSync(packageName, userId, false);
19378                }
19379                if (observer != null) {
19380                    try {
19381                        observer.onRemoveCompleted(packageName, true);
19382                    } catch (RemoteException e) {
19383                        Log.i(TAG, "Observer no longer exists.");
19384                    }
19385                }
19386            }
19387        });
19388    }
19389
19390    @Override
19391    public void getPackageSizeInfo(final String packageName, int userHandle,
19392            final IPackageStatsObserver observer) {
19393        throw new UnsupportedOperationException(
19394                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19395    }
19396
19397    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19398        final PackageSetting ps;
19399        synchronized (mPackages) {
19400            ps = mSettings.mPackages.get(packageName);
19401            if (ps == null) {
19402                Slog.w(TAG, "Failed to find settings for " + packageName);
19403                return false;
19404            }
19405        }
19406
19407        final String[] packageNames = { packageName };
19408        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19409        final String[] codePaths = { ps.codePathString };
19410
19411        try {
19412            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19413                    ps.appId, ceDataInodes, codePaths, stats);
19414
19415            // For now, ignore code size of packages on system partition
19416            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19417                stats.codeSize = 0;
19418            }
19419
19420            // External clients expect these to be tracked separately
19421            stats.dataSize -= stats.cacheSize;
19422
19423        } catch (InstallerException e) {
19424            Slog.w(TAG, String.valueOf(e));
19425            return false;
19426        }
19427
19428        return true;
19429    }
19430
19431    private int getUidTargetSdkVersionLockedLPr(int uid) {
19432        Object obj = mSettings.getUserIdLPr(uid);
19433        if (obj instanceof SharedUserSetting) {
19434            final SharedUserSetting sus = (SharedUserSetting) obj;
19435            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19436            final Iterator<PackageSetting> it = sus.packages.iterator();
19437            while (it.hasNext()) {
19438                final PackageSetting ps = it.next();
19439                if (ps.pkg != null) {
19440                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19441                    if (v < vers) vers = v;
19442                }
19443            }
19444            return vers;
19445        } else if (obj instanceof PackageSetting) {
19446            final PackageSetting ps = (PackageSetting) obj;
19447            if (ps.pkg != null) {
19448                return ps.pkg.applicationInfo.targetSdkVersion;
19449            }
19450        }
19451        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19452    }
19453
19454    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19455        final PackageParser.Package p = mPackages.get(packageName);
19456        if (p != null) {
19457            return p.applicationInfo.targetSdkVersion;
19458        }
19459        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19460    }
19461
19462    @Override
19463    public void addPreferredActivity(IntentFilter filter, int match,
19464            ComponentName[] set, ComponentName activity, int userId) {
19465        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19466                "Adding preferred");
19467    }
19468
19469    private void addPreferredActivityInternal(IntentFilter filter, int match,
19470            ComponentName[] set, ComponentName activity, boolean always, int userId,
19471            String opname) {
19472        // writer
19473        int callingUid = Binder.getCallingUid();
19474        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19475                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19476        if (filter.countActions() == 0) {
19477            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19478            return;
19479        }
19480        synchronized (mPackages) {
19481            if (mContext.checkCallingOrSelfPermission(
19482                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19483                    != PackageManager.PERMISSION_GRANTED) {
19484                if (getUidTargetSdkVersionLockedLPr(callingUid)
19485                        < Build.VERSION_CODES.FROYO) {
19486                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19487                            + callingUid);
19488                    return;
19489                }
19490                mContext.enforceCallingOrSelfPermission(
19491                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19492            }
19493
19494            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19495            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19496                    + userId + ":");
19497            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19498            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19499            scheduleWritePackageRestrictionsLocked(userId);
19500            postPreferredActivityChangedBroadcast(userId);
19501        }
19502    }
19503
19504    private void postPreferredActivityChangedBroadcast(int userId) {
19505        mHandler.post(() -> {
19506            final IActivityManager am = ActivityManager.getService();
19507            if (am == null) {
19508                return;
19509            }
19510
19511            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19512            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19513            try {
19514                am.broadcastIntent(null, intent, null, null,
19515                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19516                        null, false, false, userId);
19517            } catch (RemoteException e) {
19518            }
19519        });
19520    }
19521
19522    @Override
19523    public void replacePreferredActivity(IntentFilter filter, int match,
19524            ComponentName[] set, ComponentName activity, int userId) {
19525        if (filter.countActions() != 1) {
19526            throw new IllegalArgumentException(
19527                    "replacePreferredActivity expects filter to have only 1 action.");
19528        }
19529        if (filter.countDataAuthorities() != 0
19530                || filter.countDataPaths() != 0
19531                || filter.countDataSchemes() > 1
19532                || filter.countDataTypes() != 0) {
19533            throw new IllegalArgumentException(
19534                    "replacePreferredActivity expects filter to have no data authorities, " +
19535                    "paths, or types; and at most one scheme.");
19536        }
19537
19538        final int callingUid = Binder.getCallingUid();
19539        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19540                true /* requireFullPermission */, false /* checkShell */,
19541                "replace preferred activity");
19542        synchronized (mPackages) {
19543            if (mContext.checkCallingOrSelfPermission(
19544                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19545                    != PackageManager.PERMISSION_GRANTED) {
19546                if (getUidTargetSdkVersionLockedLPr(callingUid)
19547                        < Build.VERSION_CODES.FROYO) {
19548                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19549                            + Binder.getCallingUid());
19550                    return;
19551                }
19552                mContext.enforceCallingOrSelfPermission(
19553                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19554            }
19555
19556            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19557            if (pir != null) {
19558                // Get all of the existing entries that exactly match this filter.
19559                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19560                if (existing != null && existing.size() == 1) {
19561                    PreferredActivity cur = existing.get(0);
19562                    if (DEBUG_PREFERRED) {
19563                        Slog.i(TAG, "Checking replace of preferred:");
19564                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19565                        if (!cur.mPref.mAlways) {
19566                            Slog.i(TAG, "  -- CUR; not mAlways!");
19567                        } else {
19568                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19569                            Slog.i(TAG, "  -- CUR: mSet="
19570                                    + Arrays.toString(cur.mPref.mSetComponents));
19571                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19572                            Slog.i(TAG, "  -- NEW: mMatch="
19573                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19574                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19575                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19576                        }
19577                    }
19578                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19579                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19580                            && cur.mPref.sameSet(set)) {
19581                        // Setting the preferred activity to what it happens to be already
19582                        if (DEBUG_PREFERRED) {
19583                            Slog.i(TAG, "Replacing with same preferred activity "
19584                                    + cur.mPref.mShortComponent + " for user "
19585                                    + userId + ":");
19586                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19587                        }
19588                        return;
19589                    }
19590                }
19591
19592                if (existing != null) {
19593                    if (DEBUG_PREFERRED) {
19594                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19595                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19596                    }
19597                    for (int i = 0; i < existing.size(); i++) {
19598                        PreferredActivity pa = existing.get(i);
19599                        if (DEBUG_PREFERRED) {
19600                            Slog.i(TAG, "Removing existing preferred activity "
19601                                    + pa.mPref.mComponent + ":");
19602                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19603                        }
19604                        pir.removeFilter(pa);
19605                    }
19606                }
19607            }
19608            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19609                    "Replacing preferred");
19610        }
19611    }
19612
19613    @Override
19614    public void clearPackagePreferredActivities(String packageName) {
19615        final int callingUid = Binder.getCallingUid();
19616        if (getInstantAppPackageName(callingUid) != null) {
19617            return;
19618        }
19619        // writer
19620        synchronized (mPackages) {
19621            PackageParser.Package pkg = mPackages.get(packageName);
19622            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19623                if (mContext.checkCallingOrSelfPermission(
19624                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19625                        != PackageManager.PERMISSION_GRANTED) {
19626                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19627                            < Build.VERSION_CODES.FROYO) {
19628                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19629                                + callingUid);
19630                        return;
19631                    }
19632                    mContext.enforceCallingOrSelfPermission(
19633                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19634                }
19635            }
19636            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19637            if (ps != null
19638                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19639                return;
19640            }
19641            int user = UserHandle.getCallingUserId();
19642            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19643                scheduleWritePackageRestrictionsLocked(user);
19644            }
19645        }
19646    }
19647
19648    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19649    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19650        ArrayList<PreferredActivity> removed = null;
19651        boolean changed = false;
19652        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19653            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19654            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19655            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19656                continue;
19657            }
19658            Iterator<PreferredActivity> it = pir.filterIterator();
19659            while (it.hasNext()) {
19660                PreferredActivity pa = it.next();
19661                // Mark entry for removal only if it matches the package name
19662                // and the entry is of type "always".
19663                if (packageName == null ||
19664                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19665                                && pa.mPref.mAlways)) {
19666                    if (removed == null) {
19667                        removed = new ArrayList<PreferredActivity>();
19668                    }
19669                    removed.add(pa);
19670                }
19671            }
19672            if (removed != null) {
19673                for (int j=0; j<removed.size(); j++) {
19674                    PreferredActivity pa = removed.get(j);
19675                    pir.removeFilter(pa);
19676                }
19677                changed = true;
19678            }
19679        }
19680        if (changed) {
19681            postPreferredActivityChangedBroadcast(userId);
19682        }
19683        return changed;
19684    }
19685
19686    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19687    private void clearIntentFilterVerificationsLPw(int userId) {
19688        final int packageCount = mPackages.size();
19689        for (int i = 0; i < packageCount; i++) {
19690            PackageParser.Package pkg = mPackages.valueAt(i);
19691            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19692        }
19693    }
19694
19695    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19696    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19697        if (userId == UserHandle.USER_ALL) {
19698            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19699                    sUserManager.getUserIds())) {
19700                for (int oneUserId : sUserManager.getUserIds()) {
19701                    scheduleWritePackageRestrictionsLocked(oneUserId);
19702                }
19703            }
19704        } else {
19705            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19706                scheduleWritePackageRestrictionsLocked(userId);
19707            }
19708        }
19709    }
19710
19711    /** Clears state for all users, and touches intent filter verification policy */
19712    void clearDefaultBrowserIfNeeded(String packageName) {
19713        for (int oneUserId : sUserManager.getUserIds()) {
19714            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19715        }
19716    }
19717
19718    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19719        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19720        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19721            if (packageName.equals(defaultBrowserPackageName)) {
19722                setDefaultBrowserPackageName(null, userId);
19723            }
19724        }
19725    }
19726
19727    @Override
19728    public void resetApplicationPreferences(int userId) {
19729        mContext.enforceCallingOrSelfPermission(
19730                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19731        final long identity = Binder.clearCallingIdentity();
19732        // writer
19733        try {
19734            synchronized (mPackages) {
19735                clearPackagePreferredActivitiesLPw(null, userId);
19736                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19737                // TODO: We have to reset the default SMS and Phone. This requires
19738                // significant refactoring to keep all default apps in the package
19739                // manager (cleaner but more work) or have the services provide
19740                // callbacks to the package manager to request a default app reset.
19741                applyFactoryDefaultBrowserLPw(userId);
19742                clearIntentFilterVerificationsLPw(userId);
19743                primeDomainVerificationsLPw(userId);
19744                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19745                scheduleWritePackageRestrictionsLocked(userId);
19746            }
19747            resetNetworkPolicies(userId);
19748        } finally {
19749            Binder.restoreCallingIdentity(identity);
19750        }
19751    }
19752
19753    @Override
19754    public int getPreferredActivities(List<IntentFilter> outFilters,
19755            List<ComponentName> outActivities, String packageName) {
19756        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19757            return 0;
19758        }
19759        int num = 0;
19760        final int userId = UserHandle.getCallingUserId();
19761        // reader
19762        synchronized (mPackages) {
19763            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19764            if (pir != null) {
19765                final Iterator<PreferredActivity> it = pir.filterIterator();
19766                while (it.hasNext()) {
19767                    final PreferredActivity pa = it.next();
19768                    if (packageName == null
19769                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19770                                    && pa.mPref.mAlways)) {
19771                        if (outFilters != null) {
19772                            outFilters.add(new IntentFilter(pa));
19773                        }
19774                        if (outActivities != null) {
19775                            outActivities.add(pa.mPref.mComponent);
19776                        }
19777                    }
19778                }
19779            }
19780        }
19781
19782        return num;
19783    }
19784
19785    @Override
19786    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19787            int userId) {
19788        int callingUid = Binder.getCallingUid();
19789        if (callingUid != Process.SYSTEM_UID) {
19790            throw new SecurityException(
19791                    "addPersistentPreferredActivity can only be run by the system");
19792        }
19793        if (filter.countActions() == 0) {
19794            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19795            return;
19796        }
19797        synchronized (mPackages) {
19798            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19799                    ":");
19800            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19801            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19802                    new PersistentPreferredActivity(filter, activity));
19803            scheduleWritePackageRestrictionsLocked(userId);
19804            postPreferredActivityChangedBroadcast(userId);
19805        }
19806    }
19807
19808    @Override
19809    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19810        int callingUid = Binder.getCallingUid();
19811        if (callingUid != Process.SYSTEM_UID) {
19812            throw new SecurityException(
19813                    "clearPackagePersistentPreferredActivities can only be run by the system");
19814        }
19815        ArrayList<PersistentPreferredActivity> removed = null;
19816        boolean changed = false;
19817        synchronized (mPackages) {
19818            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19819                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19820                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19821                        .valueAt(i);
19822                if (userId != thisUserId) {
19823                    continue;
19824                }
19825                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19826                while (it.hasNext()) {
19827                    PersistentPreferredActivity ppa = it.next();
19828                    // Mark entry for removal only if it matches the package name.
19829                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19830                        if (removed == null) {
19831                            removed = new ArrayList<PersistentPreferredActivity>();
19832                        }
19833                        removed.add(ppa);
19834                    }
19835                }
19836                if (removed != null) {
19837                    for (int j=0; j<removed.size(); j++) {
19838                        PersistentPreferredActivity ppa = removed.get(j);
19839                        ppir.removeFilter(ppa);
19840                    }
19841                    changed = true;
19842                }
19843            }
19844
19845            if (changed) {
19846                scheduleWritePackageRestrictionsLocked(userId);
19847                postPreferredActivityChangedBroadcast(userId);
19848            }
19849        }
19850    }
19851
19852    /**
19853     * Common machinery for picking apart a restored XML blob and passing
19854     * it to a caller-supplied functor to be applied to the running system.
19855     */
19856    private void restoreFromXml(XmlPullParser parser, int userId,
19857            String expectedStartTag, BlobXmlRestorer functor)
19858            throws IOException, XmlPullParserException {
19859        int type;
19860        while ((type = parser.next()) != XmlPullParser.START_TAG
19861                && type != XmlPullParser.END_DOCUMENT) {
19862        }
19863        if (type != XmlPullParser.START_TAG) {
19864            // oops didn't find a start tag?!
19865            if (DEBUG_BACKUP) {
19866                Slog.e(TAG, "Didn't find start tag during restore");
19867            }
19868            return;
19869        }
19870Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19871        // this is supposed to be TAG_PREFERRED_BACKUP
19872        if (!expectedStartTag.equals(parser.getName())) {
19873            if (DEBUG_BACKUP) {
19874                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19875            }
19876            return;
19877        }
19878
19879        // skip interfering stuff, then we're aligned with the backing implementation
19880        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19881Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19882        functor.apply(parser, userId);
19883    }
19884
19885    private interface BlobXmlRestorer {
19886        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19887    }
19888
19889    /**
19890     * Non-Binder method, support for the backup/restore mechanism: write the
19891     * full set of preferred activities in its canonical XML format.  Returns the
19892     * XML output as a byte array, or null if there is none.
19893     */
19894    @Override
19895    public byte[] getPreferredActivityBackup(int userId) {
19896        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19897            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19898        }
19899
19900        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19901        try {
19902            final XmlSerializer serializer = new FastXmlSerializer();
19903            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19904            serializer.startDocument(null, true);
19905            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19906
19907            synchronized (mPackages) {
19908                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19909            }
19910
19911            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19912            serializer.endDocument();
19913            serializer.flush();
19914        } catch (Exception e) {
19915            if (DEBUG_BACKUP) {
19916                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19917            }
19918            return null;
19919        }
19920
19921        return dataStream.toByteArray();
19922    }
19923
19924    @Override
19925    public void restorePreferredActivities(byte[] backup, int userId) {
19926        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19927            throw new SecurityException("Only the system may call restorePreferredActivities()");
19928        }
19929
19930        try {
19931            final XmlPullParser parser = Xml.newPullParser();
19932            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19933            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19934                    new BlobXmlRestorer() {
19935                        @Override
19936                        public void apply(XmlPullParser parser, int userId)
19937                                throws XmlPullParserException, IOException {
19938                            synchronized (mPackages) {
19939                                mSettings.readPreferredActivitiesLPw(parser, userId);
19940                            }
19941                        }
19942                    } );
19943        } catch (Exception e) {
19944            if (DEBUG_BACKUP) {
19945                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19946            }
19947        }
19948    }
19949
19950    /**
19951     * Non-Binder method, support for the backup/restore mechanism: write the
19952     * default browser (etc) settings in its canonical XML format.  Returns the default
19953     * browser XML representation as a byte array, or null if there is none.
19954     */
19955    @Override
19956    public byte[] getDefaultAppsBackup(int userId) {
19957        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19958            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19959        }
19960
19961        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19962        try {
19963            final XmlSerializer serializer = new FastXmlSerializer();
19964            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19965            serializer.startDocument(null, true);
19966            serializer.startTag(null, TAG_DEFAULT_APPS);
19967
19968            synchronized (mPackages) {
19969                mSettings.writeDefaultAppsLPr(serializer, userId);
19970            }
19971
19972            serializer.endTag(null, TAG_DEFAULT_APPS);
19973            serializer.endDocument();
19974            serializer.flush();
19975        } catch (Exception e) {
19976            if (DEBUG_BACKUP) {
19977                Slog.e(TAG, "Unable to write default apps for backup", e);
19978            }
19979            return null;
19980        }
19981
19982        return dataStream.toByteArray();
19983    }
19984
19985    @Override
19986    public void restoreDefaultApps(byte[] backup, int userId) {
19987        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19988            throw new SecurityException("Only the system may call restoreDefaultApps()");
19989        }
19990
19991        try {
19992            final XmlPullParser parser = Xml.newPullParser();
19993            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19994            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19995                    new BlobXmlRestorer() {
19996                        @Override
19997                        public void apply(XmlPullParser parser, int userId)
19998                                throws XmlPullParserException, IOException {
19999                            synchronized (mPackages) {
20000                                mSettings.readDefaultAppsLPw(parser, userId);
20001                            }
20002                        }
20003                    } );
20004        } catch (Exception e) {
20005            if (DEBUG_BACKUP) {
20006                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20007            }
20008        }
20009    }
20010
20011    @Override
20012    public byte[] getIntentFilterVerificationBackup(int userId) {
20013        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20014            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20015        }
20016
20017        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20018        try {
20019            final XmlSerializer serializer = new FastXmlSerializer();
20020            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20021            serializer.startDocument(null, true);
20022            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20023
20024            synchronized (mPackages) {
20025                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20026            }
20027
20028            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20029            serializer.endDocument();
20030            serializer.flush();
20031        } catch (Exception e) {
20032            if (DEBUG_BACKUP) {
20033                Slog.e(TAG, "Unable to write default apps for backup", e);
20034            }
20035            return null;
20036        }
20037
20038        return dataStream.toByteArray();
20039    }
20040
20041    @Override
20042    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20043        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20044            throw new SecurityException("Only the system may call restorePreferredActivities()");
20045        }
20046
20047        try {
20048            final XmlPullParser parser = Xml.newPullParser();
20049            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20050            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20051                    new BlobXmlRestorer() {
20052                        @Override
20053                        public void apply(XmlPullParser parser, int userId)
20054                                throws XmlPullParserException, IOException {
20055                            synchronized (mPackages) {
20056                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20057                                mSettings.writeLPr();
20058                            }
20059                        }
20060                    } );
20061        } catch (Exception e) {
20062            if (DEBUG_BACKUP) {
20063                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20064            }
20065        }
20066    }
20067
20068    @Override
20069    public byte[] getPermissionGrantBackup(int userId) {
20070        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20071            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20072        }
20073
20074        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20075        try {
20076            final XmlSerializer serializer = new FastXmlSerializer();
20077            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20078            serializer.startDocument(null, true);
20079            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20080
20081            synchronized (mPackages) {
20082                serializeRuntimePermissionGrantsLPr(serializer, userId);
20083            }
20084
20085            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20086            serializer.endDocument();
20087            serializer.flush();
20088        } catch (Exception e) {
20089            if (DEBUG_BACKUP) {
20090                Slog.e(TAG, "Unable to write default apps for backup", e);
20091            }
20092            return null;
20093        }
20094
20095        return dataStream.toByteArray();
20096    }
20097
20098    @Override
20099    public void restorePermissionGrants(byte[] backup, int userId) {
20100        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20101            throw new SecurityException("Only the system may call restorePermissionGrants()");
20102        }
20103
20104        try {
20105            final XmlPullParser parser = Xml.newPullParser();
20106            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20107            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20108                    new BlobXmlRestorer() {
20109                        @Override
20110                        public void apply(XmlPullParser parser, int userId)
20111                                throws XmlPullParserException, IOException {
20112                            synchronized (mPackages) {
20113                                processRestoredPermissionGrantsLPr(parser, userId);
20114                            }
20115                        }
20116                    } );
20117        } catch (Exception e) {
20118            if (DEBUG_BACKUP) {
20119                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20120            }
20121        }
20122    }
20123
20124    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20125            throws IOException {
20126        serializer.startTag(null, TAG_ALL_GRANTS);
20127
20128        final int N = mSettings.mPackages.size();
20129        for (int i = 0; i < N; i++) {
20130            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20131            boolean pkgGrantsKnown = false;
20132
20133            PermissionsState packagePerms = ps.getPermissionsState();
20134
20135            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20136                final int grantFlags = state.getFlags();
20137                // only look at grants that are not system/policy fixed
20138                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20139                    final boolean isGranted = state.isGranted();
20140                    // And only back up the user-twiddled state bits
20141                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20142                        final String packageName = mSettings.mPackages.keyAt(i);
20143                        if (!pkgGrantsKnown) {
20144                            serializer.startTag(null, TAG_GRANT);
20145                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20146                            pkgGrantsKnown = true;
20147                        }
20148
20149                        final boolean userSet =
20150                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20151                        final boolean userFixed =
20152                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20153                        final boolean revoke =
20154                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20155
20156                        serializer.startTag(null, TAG_PERMISSION);
20157                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20158                        if (isGranted) {
20159                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20160                        }
20161                        if (userSet) {
20162                            serializer.attribute(null, ATTR_USER_SET, "true");
20163                        }
20164                        if (userFixed) {
20165                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20166                        }
20167                        if (revoke) {
20168                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20169                        }
20170                        serializer.endTag(null, TAG_PERMISSION);
20171                    }
20172                }
20173            }
20174
20175            if (pkgGrantsKnown) {
20176                serializer.endTag(null, TAG_GRANT);
20177            }
20178        }
20179
20180        serializer.endTag(null, TAG_ALL_GRANTS);
20181    }
20182
20183    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20184            throws XmlPullParserException, IOException {
20185        String pkgName = null;
20186        int outerDepth = parser.getDepth();
20187        int type;
20188        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20189                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20190            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20191                continue;
20192            }
20193
20194            final String tagName = parser.getName();
20195            if (tagName.equals(TAG_GRANT)) {
20196                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20197                if (DEBUG_BACKUP) {
20198                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20199                }
20200            } else if (tagName.equals(TAG_PERMISSION)) {
20201
20202                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20203                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20204
20205                int newFlagSet = 0;
20206                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20207                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20208                }
20209                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20210                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20211                }
20212                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20213                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20214                }
20215                if (DEBUG_BACKUP) {
20216                    Slog.v(TAG, "  + Restoring grant:"
20217                            + " pkg=" + pkgName
20218                            + " perm=" + permName
20219                            + " granted=" + isGranted
20220                            + " bits=0x" + Integer.toHexString(newFlagSet));
20221                }
20222                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20223                if (ps != null) {
20224                    // Already installed so we apply the grant immediately
20225                    if (DEBUG_BACKUP) {
20226                        Slog.v(TAG, "        + already installed; applying");
20227                    }
20228                    PermissionsState perms = ps.getPermissionsState();
20229                    BasePermission bp =
20230                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20231                    if (bp != null) {
20232                        if (isGranted) {
20233                            perms.grantRuntimePermission(bp, userId);
20234                        }
20235                        if (newFlagSet != 0) {
20236                            perms.updatePermissionFlags(
20237                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20238                        }
20239                    }
20240                } else {
20241                    // Need to wait for post-restore install to apply the grant
20242                    if (DEBUG_BACKUP) {
20243                        Slog.v(TAG, "        - not yet installed; saving for later");
20244                    }
20245                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20246                            isGranted, newFlagSet, userId);
20247                }
20248            } else {
20249                PackageManagerService.reportSettingsProblem(Log.WARN,
20250                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20251                XmlUtils.skipCurrentTag(parser);
20252            }
20253        }
20254
20255        scheduleWriteSettingsLocked();
20256        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20257    }
20258
20259    @Override
20260    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20261            int sourceUserId, int targetUserId, int flags) {
20262        mContext.enforceCallingOrSelfPermission(
20263                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20264        int callingUid = Binder.getCallingUid();
20265        enforceOwnerRights(ownerPackage, callingUid);
20266        PackageManagerServiceUtils.enforceShellRestriction(
20267                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20268        if (intentFilter.countActions() == 0) {
20269            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20270            return;
20271        }
20272        synchronized (mPackages) {
20273            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20274                    ownerPackage, targetUserId, flags);
20275            CrossProfileIntentResolver resolver =
20276                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20277            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20278            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20279            if (existing != null) {
20280                int size = existing.size();
20281                for (int i = 0; i < size; i++) {
20282                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20283                        return;
20284                    }
20285                }
20286            }
20287            resolver.addFilter(newFilter);
20288            scheduleWritePackageRestrictionsLocked(sourceUserId);
20289        }
20290    }
20291
20292    @Override
20293    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20294        mContext.enforceCallingOrSelfPermission(
20295                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20296        final int callingUid = Binder.getCallingUid();
20297        enforceOwnerRights(ownerPackage, callingUid);
20298        PackageManagerServiceUtils.enforceShellRestriction(
20299                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20300        synchronized (mPackages) {
20301            CrossProfileIntentResolver resolver =
20302                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20303            ArraySet<CrossProfileIntentFilter> set =
20304                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20305            for (CrossProfileIntentFilter filter : set) {
20306                if (filter.getOwnerPackage().equals(ownerPackage)) {
20307                    resolver.removeFilter(filter);
20308                }
20309            }
20310            scheduleWritePackageRestrictionsLocked(sourceUserId);
20311        }
20312    }
20313
20314    // Enforcing that callingUid is owning pkg on userId
20315    private void enforceOwnerRights(String pkg, int callingUid) {
20316        // The system owns everything.
20317        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20318            return;
20319        }
20320        final int callingUserId = UserHandle.getUserId(callingUid);
20321        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20322        if (pi == null) {
20323            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20324                    + callingUserId);
20325        }
20326        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20327            throw new SecurityException("Calling uid " + callingUid
20328                    + " does not own package " + pkg);
20329        }
20330    }
20331
20332    @Override
20333    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20334        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20335            return null;
20336        }
20337        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20338    }
20339
20340    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20341        UserManagerService ums = UserManagerService.getInstance();
20342        if (ums != null) {
20343            final UserInfo parent = ums.getProfileParent(userId);
20344            final int launcherUid = (parent != null) ? parent.id : userId;
20345            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20346            if (launcherComponent != null) {
20347                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20348                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20349                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20350                        .setPackage(launcherComponent.getPackageName());
20351                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20352            }
20353        }
20354    }
20355
20356    /**
20357     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20358     * then reports the most likely home activity or null if there are more than one.
20359     */
20360    private ComponentName getDefaultHomeActivity(int userId) {
20361        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20362        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20363        if (cn != null) {
20364            return cn;
20365        }
20366
20367        // Find the launcher with the highest priority and return that component if there are no
20368        // other home activity with the same priority.
20369        int lastPriority = Integer.MIN_VALUE;
20370        ComponentName lastComponent = null;
20371        final int size = allHomeCandidates.size();
20372        for (int i = 0; i < size; i++) {
20373            final ResolveInfo ri = allHomeCandidates.get(i);
20374            if (ri.priority > lastPriority) {
20375                lastComponent = ri.activityInfo.getComponentName();
20376                lastPriority = ri.priority;
20377            } else if (ri.priority == lastPriority) {
20378                // Two components found with same priority.
20379                lastComponent = null;
20380            }
20381        }
20382        return lastComponent;
20383    }
20384
20385    private Intent getHomeIntent() {
20386        Intent intent = new Intent(Intent.ACTION_MAIN);
20387        intent.addCategory(Intent.CATEGORY_HOME);
20388        intent.addCategory(Intent.CATEGORY_DEFAULT);
20389        return intent;
20390    }
20391
20392    private IntentFilter getHomeFilter() {
20393        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20394        filter.addCategory(Intent.CATEGORY_HOME);
20395        filter.addCategory(Intent.CATEGORY_DEFAULT);
20396        return filter;
20397    }
20398
20399    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20400            int userId) {
20401        Intent intent  = getHomeIntent();
20402        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20403                PackageManager.GET_META_DATA, userId);
20404        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20405                true, false, false, userId);
20406
20407        allHomeCandidates.clear();
20408        if (list != null) {
20409            for (ResolveInfo ri : list) {
20410                allHomeCandidates.add(ri);
20411            }
20412        }
20413        return (preferred == null || preferred.activityInfo == null)
20414                ? null
20415                : new ComponentName(preferred.activityInfo.packageName,
20416                        preferred.activityInfo.name);
20417    }
20418
20419    @Override
20420    public void setHomeActivity(ComponentName comp, int userId) {
20421        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20422            return;
20423        }
20424        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20425        getHomeActivitiesAsUser(homeActivities, userId);
20426
20427        boolean found = false;
20428
20429        final int size = homeActivities.size();
20430        final ComponentName[] set = new ComponentName[size];
20431        for (int i = 0; i < size; i++) {
20432            final ResolveInfo candidate = homeActivities.get(i);
20433            final ActivityInfo info = candidate.activityInfo;
20434            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20435            set[i] = activityName;
20436            if (!found && activityName.equals(comp)) {
20437                found = true;
20438            }
20439        }
20440        if (!found) {
20441            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20442                    + userId);
20443        }
20444        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20445                set, comp, userId);
20446    }
20447
20448    private @Nullable String getSetupWizardPackageName() {
20449        final Intent intent = new Intent(Intent.ACTION_MAIN);
20450        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20451
20452        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20453                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20454                        | MATCH_DISABLED_COMPONENTS,
20455                UserHandle.myUserId());
20456        if (matches.size() == 1) {
20457            return matches.get(0).getComponentInfo().packageName;
20458        } else {
20459            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20460                    + ": matches=" + matches);
20461            return null;
20462        }
20463    }
20464
20465    private @Nullable String getStorageManagerPackageName() {
20466        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20467
20468        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20469                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20470                        | MATCH_DISABLED_COMPONENTS,
20471                UserHandle.myUserId());
20472        if (matches.size() == 1) {
20473            return matches.get(0).getComponentInfo().packageName;
20474        } else {
20475            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20476                    + matches.size() + ": matches=" + matches);
20477            return null;
20478        }
20479    }
20480
20481    @Override
20482    public String getSystemTextClassifierPackageName() {
20483        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20484    }
20485
20486    @Override
20487    public void setApplicationEnabledSetting(String appPackageName,
20488            int newState, int flags, int userId, String callingPackage) {
20489        if (!sUserManager.exists(userId)) return;
20490        if (callingPackage == null) {
20491            callingPackage = Integer.toString(Binder.getCallingUid());
20492        }
20493        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20494    }
20495
20496    @Override
20497    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20498        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20499        synchronized (mPackages) {
20500            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20501            if (pkgSetting != null) {
20502                pkgSetting.setUpdateAvailable(updateAvailable);
20503            }
20504        }
20505    }
20506
20507    @Override
20508    public void setComponentEnabledSetting(ComponentName componentName,
20509            int newState, int flags, int userId) {
20510        if (!sUserManager.exists(userId)) return;
20511        setEnabledSetting(componentName.getPackageName(),
20512                componentName.getClassName(), newState, flags, userId, null);
20513    }
20514
20515    private void setEnabledSetting(final String packageName, String className, int newState,
20516            final int flags, int userId, String callingPackage) {
20517        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20518              || newState == COMPONENT_ENABLED_STATE_ENABLED
20519              || newState == COMPONENT_ENABLED_STATE_DISABLED
20520              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20521              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20522            throw new IllegalArgumentException("Invalid new component state: "
20523                    + newState);
20524        }
20525        PackageSetting pkgSetting;
20526        final int callingUid = Binder.getCallingUid();
20527        final int permission;
20528        if (callingUid == Process.SYSTEM_UID) {
20529            permission = PackageManager.PERMISSION_GRANTED;
20530        } else {
20531            permission = mContext.checkCallingOrSelfPermission(
20532                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20533        }
20534        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20535                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20536        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20537        boolean sendNow = false;
20538        boolean isApp = (className == null);
20539        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20540        String componentName = isApp ? packageName : className;
20541        int packageUid = -1;
20542        ArrayList<String> components;
20543
20544        // reader
20545        synchronized (mPackages) {
20546            pkgSetting = mSettings.mPackages.get(packageName);
20547            if (pkgSetting == null) {
20548                if (!isCallerInstantApp) {
20549                    if (className == null) {
20550                        throw new IllegalArgumentException("Unknown package: " + packageName);
20551                    }
20552                    throw new IllegalArgumentException(
20553                            "Unknown component: " + packageName + "/" + className);
20554                } else {
20555                    // throw SecurityException to prevent leaking package information
20556                    throw new SecurityException(
20557                            "Attempt to change component state; "
20558                            + "pid=" + Binder.getCallingPid()
20559                            + ", uid=" + callingUid
20560                            + (className == null
20561                                    ? ", package=" + packageName
20562                                    : ", component=" + packageName + "/" + className));
20563                }
20564            }
20565        }
20566
20567        // Limit who can change which apps
20568        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20569            // Don't allow apps that don't have permission to modify other apps
20570            if (!allowedByPermission
20571                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20572                throw new SecurityException(
20573                        "Attempt to change component state; "
20574                        + "pid=" + Binder.getCallingPid()
20575                        + ", uid=" + callingUid
20576                        + (className == null
20577                                ? ", package=" + packageName
20578                                : ", component=" + packageName + "/" + className));
20579            }
20580            // Don't allow changing protected packages.
20581            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20582                throw new SecurityException("Cannot disable a protected package: " + packageName);
20583            }
20584        }
20585
20586        synchronized (mPackages) {
20587            if (callingUid == Process.SHELL_UID
20588                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20589                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20590                // unless it is a test package.
20591                int oldState = pkgSetting.getEnabled(userId);
20592                if (className == null
20593                        &&
20594                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20595                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20596                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20597                        &&
20598                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20599                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20600                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20601                    // ok
20602                } else {
20603                    throw new SecurityException(
20604                            "Shell cannot change component state for " + packageName + "/"
20605                                    + className + " to " + newState);
20606                }
20607            }
20608        }
20609        if (className == null) {
20610            // We're dealing with an application/package level state change
20611            synchronized (mPackages) {
20612                if (pkgSetting.getEnabled(userId) == newState) {
20613                    // Nothing to do
20614                    return;
20615                }
20616            }
20617            // If we're enabling a system stub, there's a little more work to do.
20618            // Prior to enabling the package, we need to decompress the APK(s) to the
20619            // data partition and then replace the version on the system partition.
20620            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20621            final boolean isSystemStub = deletedPkg.isStub
20622                    && deletedPkg.isSystem();
20623            if (isSystemStub
20624                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20625                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20626                final File codePath = decompressPackage(deletedPkg);
20627                if (codePath == null) {
20628                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20629                    return;
20630                }
20631                // TODO remove direct parsing of the package object during internal cleanup
20632                // of scan package
20633                // We need to call parse directly here for no other reason than we need
20634                // the new package in order to disable the old one [we use the information
20635                // for some internal optimization to optionally create a new package setting
20636                // object on replace]. However, we can't get the package from the scan
20637                // because the scan modifies live structures and we need to remove the
20638                // old [system] package from the system before a scan can be attempted.
20639                // Once scan is indempotent we can remove this parse and use the package
20640                // object we scanned, prior to adding it to package settings.
20641                final PackageParser pp = new PackageParser();
20642                pp.setSeparateProcesses(mSeparateProcesses);
20643                pp.setDisplayMetrics(mMetrics);
20644                pp.setCallback(mPackageParserCallback);
20645                final PackageParser.Package tmpPkg;
20646                try {
20647                    final @ParseFlags int parseFlags = mDefParseFlags
20648                            | PackageParser.PARSE_MUST_BE_APK
20649                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20650                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20651                } catch (PackageParserException e) {
20652                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20653                    return;
20654                }
20655                synchronized (mInstallLock) {
20656                    // Disable the stub and remove any package entries
20657                    removePackageLI(deletedPkg, true);
20658                    synchronized (mPackages) {
20659                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20660                    }
20661                    final PackageParser.Package pkg;
20662                    try (PackageFreezer freezer =
20663                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20664                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20665                                | PackageParser.PARSE_ENFORCE_CODE;
20666                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20667                                0 /*currentTime*/, null /*user*/);
20668                        prepareAppDataAfterInstallLIF(pkg);
20669                        synchronized (mPackages) {
20670                            try {
20671                                updateSharedLibrariesLPr(pkg, null);
20672                            } catch (PackageManagerException e) {
20673                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20674                            }
20675                            mPermissionManager.updatePermissions(
20676                                    pkg.packageName, pkg, true, mPackages.values(),
20677                                    mPermissionCallback);
20678                            mSettings.writeLPr();
20679                        }
20680                    } catch (PackageManagerException e) {
20681                        // Whoops! Something went wrong; try to roll back to the stub
20682                        Slog.w(TAG, "Failed to install compressed system package:"
20683                                + pkgSetting.name, e);
20684                        // Remove the failed install
20685                        removeCodePathLI(codePath);
20686
20687                        // Install the system package
20688                        try (PackageFreezer freezer =
20689                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20690                            synchronized (mPackages) {
20691                                // NOTE: The system package always needs to be enabled; even
20692                                // if it's for a compressed stub. If we don't, installing the
20693                                // system package fails during scan [scanning checks the disabled
20694                                // packages]. We will reverse this later, after we've "installed"
20695                                // the stub.
20696                                // This leaves us in a fragile state; the stub should never be
20697                                // enabled, so, cross your fingers and hope nothing goes wrong
20698                                // until we can disable the package later.
20699                                enableSystemPackageLPw(deletedPkg);
20700                            }
20701                            installPackageFromSystemLIF(deletedPkg.codePath,
20702                                    false /*isPrivileged*/, null /*allUserHandles*/,
20703                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20704                                    true /*writeSettings*/);
20705                        } catch (PackageManagerException pme) {
20706                            Slog.w(TAG, "Failed to restore system package:"
20707                                    + deletedPkg.packageName, pme);
20708                        } finally {
20709                            synchronized (mPackages) {
20710                                mSettings.disableSystemPackageLPw(
20711                                        deletedPkg.packageName, true /*replaced*/);
20712                                mSettings.writeLPr();
20713                            }
20714                        }
20715                        return;
20716                    }
20717                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20718                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20719                    mDexManager.notifyPackageUpdated(pkg.packageName,
20720                            pkg.baseCodePath, pkg.splitCodePaths);
20721                }
20722            }
20723            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20724                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20725                // Don't care about who enables an app.
20726                callingPackage = null;
20727            }
20728            synchronized (mPackages) {
20729                pkgSetting.setEnabled(newState, userId, callingPackage);
20730            }
20731        } else {
20732            synchronized (mPackages) {
20733                // We're dealing with a component level state change
20734                // First, verify that this is a valid class name.
20735                PackageParser.Package pkg = pkgSetting.pkg;
20736                if (pkg == null || !pkg.hasComponentClassName(className)) {
20737                    if (pkg != null &&
20738                            pkg.applicationInfo.targetSdkVersion >=
20739                                    Build.VERSION_CODES.JELLY_BEAN) {
20740                        throw new IllegalArgumentException("Component class " + className
20741                                + " does not exist in " + packageName);
20742                    } else {
20743                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20744                                + className + " does not exist in " + packageName);
20745                    }
20746                }
20747                switch (newState) {
20748                    case COMPONENT_ENABLED_STATE_ENABLED:
20749                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20750                            return;
20751                        }
20752                        break;
20753                    case COMPONENT_ENABLED_STATE_DISABLED:
20754                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20755                            return;
20756                        }
20757                        break;
20758                    case COMPONENT_ENABLED_STATE_DEFAULT:
20759                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20760                            return;
20761                        }
20762                        break;
20763                    default:
20764                        Slog.e(TAG, "Invalid new component state: " + newState);
20765                        return;
20766                }
20767            }
20768        }
20769        synchronized (mPackages) {
20770            scheduleWritePackageRestrictionsLocked(userId);
20771            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20772            final long callingId = Binder.clearCallingIdentity();
20773            try {
20774                updateInstantAppInstallerLocked(packageName);
20775            } finally {
20776                Binder.restoreCallingIdentity(callingId);
20777            }
20778            components = mPendingBroadcasts.get(userId, packageName);
20779            final boolean newPackage = components == null;
20780            if (newPackage) {
20781                components = new ArrayList<String>();
20782            }
20783            if (!components.contains(componentName)) {
20784                components.add(componentName);
20785            }
20786            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20787                sendNow = true;
20788                // Purge entry from pending broadcast list if another one exists already
20789                // since we are sending one right away.
20790                mPendingBroadcasts.remove(userId, packageName);
20791            } else {
20792                if (newPackage) {
20793                    mPendingBroadcasts.put(userId, packageName, components);
20794                }
20795                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20796                    // Schedule a message
20797                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20798                }
20799            }
20800        }
20801
20802        long callingId = Binder.clearCallingIdentity();
20803        try {
20804            if (sendNow) {
20805                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20806                sendPackageChangedBroadcast(packageName,
20807                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20808            }
20809        } finally {
20810            Binder.restoreCallingIdentity(callingId);
20811        }
20812    }
20813
20814    @Override
20815    public void flushPackageRestrictionsAsUser(int userId) {
20816        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20817            return;
20818        }
20819        if (!sUserManager.exists(userId)) {
20820            return;
20821        }
20822        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20823                false /* checkShell */, "flushPackageRestrictions");
20824        synchronized (mPackages) {
20825            mSettings.writePackageRestrictionsLPr(userId);
20826            mDirtyUsers.remove(userId);
20827            if (mDirtyUsers.isEmpty()) {
20828                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20829            }
20830        }
20831    }
20832
20833    private void sendPackageChangedBroadcast(String packageName,
20834            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20835        if (DEBUG_INSTALL)
20836            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20837                    + componentNames);
20838        Bundle extras = new Bundle(4);
20839        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20840        String nameList[] = new String[componentNames.size()];
20841        componentNames.toArray(nameList);
20842        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20843        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20844        extras.putInt(Intent.EXTRA_UID, packageUid);
20845        // If this is not reporting a change of the overall package, then only send it
20846        // to registered receivers.  We don't want to launch a swath of apps for every
20847        // little component state change.
20848        final int flags = !componentNames.contains(packageName)
20849                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20850        final int userId = UserHandle.getUserId(packageUid);
20851        final boolean isInstantApp = isInstantApp(packageName, userId);
20852        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20853        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20854        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20855                userIds, instantUserIds);
20856    }
20857
20858    @Override
20859    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20860        if (!sUserManager.exists(userId)) return;
20861        final int callingUid = Binder.getCallingUid();
20862        if (getInstantAppPackageName(callingUid) != null) {
20863            return;
20864        }
20865        final int permission = mContext.checkCallingOrSelfPermission(
20866                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20867        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20868        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20869                true /* requireFullPermission */, true /* checkShell */, "stop package");
20870        // writer
20871        synchronized (mPackages) {
20872            final PackageSetting ps = mSettings.mPackages.get(packageName);
20873            if (!filterAppAccessLPr(ps, callingUid, userId)
20874                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20875                            allowedByPermission, callingUid, userId)) {
20876                scheduleWritePackageRestrictionsLocked(userId);
20877            }
20878        }
20879    }
20880
20881    @Override
20882    public String getInstallerPackageName(String packageName) {
20883        final int callingUid = Binder.getCallingUid();
20884        synchronized (mPackages) {
20885            final PackageSetting ps = mSettings.mPackages.get(packageName);
20886            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20887                return null;
20888            }
20889            return mSettings.getInstallerPackageNameLPr(packageName);
20890        }
20891    }
20892
20893    public boolean isOrphaned(String packageName) {
20894        // reader
20895        synchronized (mPackages) {
20896            return mSettings.isOrphaned(packageName);
20897        }
20898    }
20899
20900    @Override
20901    public int getApplicationEnabledSetting(String packageName, int userId) {
20902        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20903        int callingUid = Binder.getCallingUid();
20904        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20905                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20906        // reader
20907        synchronized (mPackages) {
20908            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20909                return COMPONENT_ENABLED_STATE_DISABLED;
20910            }
20911            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20912        }
20913    }
20914
20915    @Override
20916    public int getComponentEnabledSetting(ComponentName component, int userId) {
20917        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20918        int callingUid = Binder.getCallingUid();
20919        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20920                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20921        synchronized (mPackages) {
20922            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20923                    component, TYPE_UNKNOWN, userId)) {
20924                return COMPONENT_ENABLED_STATE_DISABLED;
20925            }
20926            return mSettings.getComponentEnabledSettingLPr(component, userId);
20927        }
20928    }
20929
20930    @Override
20931    public void enterSafeMode() {
20932        enforceSystemOrRoot("Only the system can request entering safe mode");
20933
20934        if (!mSystemReady) {
20935            mSafeMode = true;
20936        }
20937    }
20938
20939    @Override
20940    public void systemReady() {
20941        enforceSystemOrRoot("Only the system can claim the system is ready");
20942
20943        mSystemReady = true;
20944        final ContentResolver resolver = mContext.getContentResolver();
20945        ContentObserver co = new ContentObserver(mHandler) {
20946            @Override
20947            public void onChange(boolean selfChange) {
20948                mWebInstantAppsDisabled =
20949                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20950                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20951            }
20952        };
20953        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20954                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20955                false, co, UserHandle.USER_SYSTEM);
20956        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20957                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20958        co.onChange(true);
20959
20960        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20961        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20962        // it is done.
20963        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20964            @Override
20965            public void onChange(boolean selfChange) {
20966                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20967                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20968                        oobEnabled == 1 ? "true" : "false");
20969            }
20970        };
20971        mContext.getContentResolver().registerContentObserver(
20972                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20973                UserHandle.USER_SYSTEM);
20974        // At boot, restore the value from the setting, which persists across reboot.
20975        privAppOobObserver.onChange(true);
20976
20977        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20978        // disabled after already being started.
20979        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20980                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20981
20982        // Read the compatibilty setting when the system is ready.
20983        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20984                mContext.getContentResolver(),
20985                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20986        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20987        if (DEBUG_SETTINGS) {
20988            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20989        }
20990
20991        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20992
20993        synchronized (mPackages) {
20994            // Verify that all of the preferred activity components actually
20995            // exist.  It is possible for applications to be updated and at
20996            // that point remove a previously declared activity component that
20997            // had been set as a preferred activity.  We try to clean this up
20998            // the next time we encounter that preferred activity, but it is
20999            // possible for the user flow to never be able to return to that
21000            // situation so here we do a sanity check to make sure we haven't
21001            // left any junk around.
21002            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21003            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21004                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21005                removed.clear();
21006                for (PreferredActivity pa : pir.filterSet()) {
21007                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21008                        removed.add(pa);
21009                    }
21010                }
21011                if (removed.size() > 0) {
21012                    for (int r=0; r<removed.size(); r++) {
21013                        PreferredActivity pa = removed.get(r);
21014                        Slog.w(TAG, "Removing dangling preferred activity: "
21015                                + pa.mPref.mComponent);
21016                        pir.removeFilter(pa);
21017                    }
21018                    mSettings.writePackageRestrictionsLPr(
21019                            mSettings.mPreferredActivities.keyAt(i));
21020                }
21021            }
21022
21023            for (int userId : UserManagerService.getInstance().getUserIds()) {
21024                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21025                    grantPermissionsUserIds = ArrayUtils.appendInt(
21026                            grantPermissionsUserIds, userId);
21027                }
21028            }
21029        }
21030        sUserManager.systemReady();
21031        // If we upgraded grant all default permissions before kicking off.
21032        for (int userId : grantPermissionsUserIds) {
21033            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21034        }
21035
21036        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21037            // If we did not grant default permissions, we preload from this the
21038            // default permission exceptions lazily to ensure we don't hit the
21039            // disk on a new user creation.
21040            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21041        }
21042
21043        // Now that we've scanned all packages, and granted any default
21044        // permissions, ensure permissions are updated. Beware of dragons if you
21045        // try optimizing this.
21046        synchronized (mPackages) {
21047            mPermissionManager.updateAllPermissions(
21048                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21049                    mPermissionCallback);
21050        }
21051
21052        // Kick off any messages waiting for system ready
21053        if (mPostSystemReadyMessages != null) {
21054            for (Message msg : mPostSystemReadyMessages) {
21055                msg.sendToTarget();
21056            }
21057            mPostSystemReadyMessages = null;
21058        }
21059
21060        // Watch for external volumes that come and go over time
21061        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21062        storage.registerListener(mStorageListener);
21063
21064        mInstallerService.systemReady();
21065        mPackageDexOptimizer.systemReady();
21066
21067        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21068                StorageManagerInternal.class);
21069        StorageManagerInternal.addExternalStoragePolicy(
21070                new StorageManagerInternal.ExternalStorageMountPolicy() {
21071            @Override
21072            public int getMountMode(int uid, String packageName) {
21073                if (Process.isIsolated(uid)) {
21074                    return Zygote.MOUNT_EXTERNAL_NONE;
21075                }
21076                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21077                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21078                }
21079                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21080                    return Zygote.MOUNT_EXTERNAL_READ;
21081                }
21082                return Zygote.MOUNT_EXTERNAL_WRITE;
21083            }
21084
21085            @Override
21086            public boolean hasExternalStorage(int uid, String packageName) {
21087                return true;
21088            }
21089        });
21090
21091        // Now that we're mostly running, clean up stale users and apps
21092        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21093        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21094
21095        mPermissionManager.systemReady();
21096
21097        if (mInstantAppResolverConnection != null) {
21098            mContext.registerReceiver(new BroadcastReceiver() {
21099                @Override
21100                public void onReceive(Context context, Intent intent) {
21101                    mInstantAppResolverConnection.optimisticBind();
21102                    mContext.unregisterReceiver(this);
21103                }
21104            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21105        }
21106    }
21107
21108    public void waitForAppDataPrepared() {
21109        if (mPrepareAppDataFuture == null) {
21110            return;
21111        }
21112        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21113        mPrepareAppDataFuture = null;
21114    }
21115
21116    @Override
21117    public boolean isSafeMode() {
21118        // allow instant applications
21119        return mSafeMode;
21120    }
21121
21122    @Override
21123    public boolean hasSystemUidErrors() {
21124        // allow instant applications
21125        return mHasSystemUidErrors;
21126    }
21127
21128    static String arrayToString(int[] array) {
21129        StringBuffer buf = new StringBuffer(128);
21130        buf.append('[');
21131        if (array != null) {
21132            for (int i=0; i<array.length; i++) {
21133                if (i > 0) buf.append(", ");
21134                buf.append(array[i]);
21135            }
21136        }
21137        buf.append(']');
21138        return buf.toString();
21139    }
21140
21141    @Override
21142    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21143            FileDescriptor err, String[] args, ShellCallback callback,
21144            ResultReceiver resultReceiver) {
21145        (new PackageManagerShellCommand(this)).exec(
21146                this, in, out, err, args, callback, resultReceiver);
21147    }
21148
21149    @Override
21150    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21151        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21152
21153        DumpState dumpState = new DumpState();
21154        boolean fullPreferred = false;
21155        boolean checkin = false;
21156
21157        String packageName = null;
21158        ArraySet<String> permissionNames = null;
21159
21160        int opti = 0;
21161        while (opti < args.length) {
21162            String opt = args[opti];
21163            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21164                break;
21165            }
21166            opti++;
21167
21168            if ("-a".equals(opt)) {
21169                // Right now we only know how to print all.
21170            } else if ("-h".equals(opt)) {
21171                pw.println("Package manager dump options:");
21172                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21173                pw.println("    --checkin: dump for a checkin");
21174                pw.println("    -f: print details of intent filters");
21175                pw.println("    -h: print this help");
21176                pw.println("  cmd may be one of:");
21177                pw.println("    l[ibraries]: list known shared libraries");
21178                pw.println("    f[eatures]: list device features");
21179                pw.println("    k[eysets]: print known keysets");
21180                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21181                pw.println("    perm[issions]: dump permissions");
21182                pw.println("    permission [name ...]: dump declaration and use of given permission");
21183                pw.println("    pref[erred]: print preferred package settings");
21184                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21185                pw.println("    prov[iders]: dump content providers");
21186                pw.println("    p[ackages]: dump installed packages");
21187                pw.println("    s[hared-users]: dump shared user IDs");
21188                pw.println("    m[essages]: print collected runtime messages");
21189                pw.println("    v[erifiers]: print package verifier info");
21190                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21191                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21192                pw.println("    version: print database version info");
21193                pw.println("    write: write current settings now");
21194                pw.println("    installs: details about install sessions");
21195                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21196                pw.println("    dexopt: dump dexopt state");
21197                pw.println("    compiler-stats: dump compiler statistics");
21198                pw.println("    service-permissions: dump permissions required by services");
21199                pw.println("    <package.name>: info about given package");
21200                return;
21201            } else if ("--checkin".equals(opt)) {
21202                checkin = true;
21203            } else if ("-f".equals(opt)) {
21204                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21205            } else if ("--proto".equals(opt)) {
21206                dumpProto(fd);
21207                return;
21208            } else {
21209                pw.println("Unknown argument: " + opt + "; use -h for help");
21210            }
21211        }
21212
21213        // Is the caller requesting to dump a particular piece of data?
21214        if (opti < args.length) {
21215            String cmd = args[opti];
21216            opti++;
21217            // Is this a package name?
21218            if ("android".equals(cmd) || cmd.contains(".")) {
21219                packageName = cmd;
21220                // When dumping a single package, we always dump all of its
21221                // filter information since the amount of data will be reasonable.
21222                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21223            } else if ("check-permission".equals(cmd)) {
21224                if (opti >= args.length) {
21225                    pw.println("Error: check-permission missing permission argument");
21226                    return;
21227                }
21228                String perm = args[opti];
21229                opti++;
21230                if (opti >= args.length) {
21231                    pw.println("Error: check-permission missing package argument");
21232                    return;
21233                }
21234
21235                String pkg = args[opti];
21236                opti++;
21237                int user = UserHandle.getUserId(Binder.getCallingUid());
21238                if (opti < args.length) {
21239                    try {
21240                        user = Integer.parseInt(args[opti]);
21241                    } catch (NumberFormatException e) {
21242                        pw.println("Error: check-permission user argument is not a number: "
21243                                + args[opti]);
21244                        return;
21245                    }
21246                }
21247
21248                // Normalize package name to handle renamed packages and static libs
21249                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21250
21251                pw.println(checkPermission(perm, pkg, user));
21252                return;
21253            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21254                dumpState.setDump(DumpState.DUMP_LIBS);
21255            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21256                dumpState.setDump(DumpState.DUMP_FEATURES);
21257            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21258                if (opti >= args.length) {
21259                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21260                            | DumpState.DUMP_SERVICE_RESOLVERS
21261                            | DumpState.DUMP_RECEIVER_RESOLVERS
21262                            | DumpState.DUMP_CONTENT_RESOLVERS);
21263                } else {
21264                    while (opti < args.length) {
21265                        String name = args[opti];
21266                        if ("a".equals(name) || "activity".equals(name)) {
21267                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21268                        } else if ("s".equals(name) || "service".equals(name)) {
21269                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21270                        } else if ("r".equals(name) || "receiver".equals(name)) {
21271                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21272                        } else if ("c".equals(name) || "content".equals(name)) {
21273                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21274                        } else {
21275                            pw.println("Error: unknown resolver table type: " + name);
21276                            return;
21277                        }
21278                        opti++;
21279                    }
21280                }
21281            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21282                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21283            } else if ("permission".equals(cmd)) {
21284                if (opti >= args.length) {
21285                    pw.println("Error: permission requires permission name");
21286                    return;
21287                }
21288                permissionNames = new ArraySet<>();
21289                while (opti < args.length) {
21290                    permissionNames.add(args[opti]);
21291                    opti++;
21292                }
21293                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21294                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21295            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21296                dumpState.setDump(DumpState.DUMP_PREFERRED);
21297            } else if ("preferred-xml".equals(cmd)) {
21298                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21299                if (opti < args.length && "--full".equals(args[opti])) {
21300                    fullPreferred = true;
21301                    opti++;
21302                }
21303            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21304                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21305            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21306                dumpState.setDump(DumpState.DUMP_PACKAGES);
21307            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21308                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21309            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21310                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21311            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21312                dumpState.setDump(DumpState.DUMP_MESSAGES);
21313            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21314                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21315            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21316                    || "intent-filter-verifiers".equals(cmd)) {
21317                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21318            } else if ("version".equals(cmd)) {
21319                dumpState.setDump(DumpState.DUMP_VERSION);
21320            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21321                dumpState.setDump(DumpState.DUMP_KEYSETS);
21322            } else if ("installs".equals(cmd)) {
21323                dumpState.setDump(DumpState.DUMP_INSTALLS);
21324            } else if ("frozen".equals(cmd)) {
21325                dumpState.setDump(DumpState.DUMP_FROZEN);
21326            } else if ("volumes".equals(cmd)) {
21327                dumpState.setDump(DumpState.DUMP_VOLUMES);
21328            } else if ("dexopt".equals(cmd)) {
21329                dumpState.setDump(DumpState.DUMP_DEXOPT);
21330            } else if ("compiler-stats".equals(cmd)) {
21331                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21332            } else if ("changes".equals(cmd)) {
21333                dumpState.setDump(DumpState.DUMP_CHANGES);
21334            } else if ("service-permissions".equals(cmd)) {
21335                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21336            } else if ("write".equals(cmd)) {
21337                synchronized (mPackages) {
21338                    mSettings.writeLPr();
21339                    pw.println("Settings written.");
21340                    return;
21341                }
21342            }
21343        }
21344
21345        if (checkin) {
21346            pw.println("vers,1");
21347        }
21348
21349        // reader
21350        synchronized (mPackages) {
21351            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21352                if (!checkin) {
21353                    if (dumpState.onTitlePrinted())
21354                        pw.println();
21355                    pw.println("Database versions:");
21356                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21357                }
21358            }
21359
21360            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21361                if (!checkin) {
21362                    if (dumpState.onTitlePrinted())
21363                        pw.println();
21364                    pw.println("Verifiers:");
21365                    pw.print("  Required: ");
21366                    pw.print(mRequiredVerifierPackage);
21367                    pw.print(" (uid=");
21368                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21369                            UserHandle.USER_SYSTEM));
21370                    pw.println(")");
21371                } else if (mRequiredVerifierPackage != null) {
21372                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21373                    pw.print(",");
21374                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21375                            UserHandle.USER_SYSTEM));
21376                }
21377            }
21378
21379            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21380                    packageName == null) {
21381                if (mIntentFilterVerifierComponent != null) {
21382                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21383                    if (!checkin) {
21384                        if (dumpState.onTitlePrinted())
21385                            pw.println();
21386                        pw.println("Intent Filter Verifier:");
21387                        pw.print("  Using: ");
21388                        pw.print(verifierPackageName);
21389                        pw.print(" (uid=");
21390                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21391                                UserHandle.USER_SYSTEM));
21392                        pw.println(")");
21393                    } else if (verifierPackageName != null) {
21394                        pw.print("ifv,"); pw.print(verifierPackageName);
21395                        pw.print(",");
21396                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21397                                UserHandle.USER_SYSTEM));
21398                    }
21399                } else {
21400                    pw.println();
21401                    pw.println("No Intent Filter Verifier available!");
21402                }
21403            }
21404
21405            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21406                boolean printedHeader = false;
21407                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21408                while (it.hasNext()) {
21409                    String libName = it.next();
21410                    LongSparseArray<SharedLibraryEntry> versionedLib
21411                            = mSharedLibraries.get(libName);
21412                    if (versionedLib == null) {
21413                        continue;
21414                    }
21415                    final int versionCount = versionedLib.size();
21416                    for (int i = 0; i < versionCount; i++) {
21417                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21418                        if (!checkin) {
21419                            if (!printedHeader) {
21420                                if (dumpState.onTitlePrinted())
21421                                    pw.println();
21422                                pw.println("Libraries:");
21423                                printedHeader = true;
21424                            }
21425                            pw.print("  ");
21426                        } else {
21427                            pw.print("lib,");
21428                        }
21429                        pw.print(libEntry.info.getName());
21430                        if (libEntry.info.isStatic()) {
21431                            pw.print(" version=" + libEntry.info.getLongVersion());
21432                        }
21433                        if (!checkin) {
21434                            pw.print(" -> ");
21435                        }
21436                        if (libEntry.path != null) {
21437                            pw.print(" (jar) ");
21438                            pw.print(libEntry.path);
21439                        } else {
21440                            pw.print(" (apk) ");
21441                            pw.print(libEntry.apk);
21442                        }
21443                        pw.println();
21444                    }
21445                }
21446            }
21447
21448            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21449                if (dumpState.onTitlePrinted())
21450                    pw.println();
21451                if (!checkin) {
21452                    pw.println("Features:");
21453                }
21454
21455                synchronized (mAvailableFeatures) {
21456                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21457                        if (checkin) {
21458                            pw.print("feat,");
21459                            pw.print(feat.name);
21460                            pw.print(",");
21461                            pw.println(feat.version);
21462                        } else {
21463                            pw.print("  ");
21464                            pw.print(feat.name);
21465                            if (feat.version > 0) {
21466                                pw.print(" version=");
21467                                pw.print(feat.version);
21468                            }
21469                            pw.println();
21470                        }
21471                    }
21472                }
21473            }
21474
21475            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21476                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21477                        : "Activity Resolver Table:", "  ", packageName,
21478                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21479                    dumpState.setTitlePrinted(true);
21480                }
21481            }
21482            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21483                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21484                        : "Receiver Resolver Table:", "  ", packageName,
21485                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21486                    dumpState.setTitlePrinted(true);
21487                }
21488            }
21489            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21490                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21491                        : "Service Resolver Table:", "  ", packageName,
21492                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21493                    dumpState.setTitlePrinted(true);
21494                }
21495            }
21496            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21497                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21498                        : "Provider Resolver Table:", "  ", packageName,
21499                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21500                    dumpState.setTitlePrinted(true);
21501                }
21502            }
21503
21504            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21505                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21506                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21507                    int user = mSettings.mPreferredActivities.keyAt(i);
21508                    if (pir.dump(pw,
21509                            dumpState.getTitlePrinted()
21510                                ? "\nPreferred Activities User " + user + ":"
21511                                : "Preferred Activities User " + user + ":", "  ",
21512                            packageName, true, false)) {
21513                        dumpState.setTitlePrinted(true);
21514                    }
21515                }
21516            }
21517
21518            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21519                pw.flush();
21520                FileOutputStream fout = new FileOutputStream(fd);
21521                BufferedOutputStream str = new BufferedOutputStream(fout);
21522                XmlSerializer serializer = new FastXmlSerializer();
21523                try {
21524                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21525                    serializer.startDocument(null, true);
21526                    serializer.setFeature(
21527                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21528                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21529                    serializer.endDocument();
21530                    serializer.flush();
21531                } catch (IllegalArgumentException e) {
21532                    pw.println("Failed writing: " + e);
21533                } catch (IllegalStateException e) {
21534                    pw.println("Failed writing: " + e);
21535                } catch (IOException e) {
21536                    pw.println("Failed writing: " + e);
21537                }
21538            }
21539
21540            if (!checkin
21541                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21542                    && packageName == null) {
21543                pw.println();
21544                int count = mSettings.mPackages.size();
21545                if (count == 0) {
21546                    pw.println("No applications!");
21547                    pw.println();
21548                } else {
21549                    final String prefix = "  ";
21550                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21551                    if (allPackageSettings.size() == 0) {
21552                        pw.println("No domain preferred apps!");
21553                        pw.println();
21554                    } else {
21555                        pw.println("App verification status:");
21556                        pw.println();
21557                        count = 0;
21558                        for (PackageSetting ps : allPackageSettings) {
21559                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21560                            if (ivi == null || ivi.getPackageName() == null) continue;
21561                            pw.println(prefix + "Package: " + ivi.getPackageName());
21562                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21563                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21564                            pw.println();
21565                            count++;
21566                        }
21567                        if (count == 0) {
21568                            pw.println(prefix + "No app verification established.");
21569                            pw.println();
21570                        }
21571                        for (int userId : sUserManager.getUserIds()) {
21572                            pw.println("App linkages for user " + userId + ":");
21573                            pw.println();
21574                            count = 0;
21575                            for (PackageSetting ps : allPackageSettings) {
21576                                final long status = ps.getDomainVerificationStatusForUser(userId);
21577                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21578                                        && !DEBUG_DOMAIN_VERIFICATION) {
21579                                    continue;
21580                                }
21581                                pw.println(prefix + "Package: " + ps.name);
21582                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21583                                String statusStr = IntentFilterVerificationInfo.
21584                                        getStatusStringFromValue(status);
21585                                pw.println(prefix + "Status:  " + statusStr);
21586                                pw.println();
21587                                count++;
21588                            }
21589                            if (count == 0) {
21590                                pw.println(prefix + "No configured app linkages.");
21591                                pw.println();
21592                            }
21593                        }
21594                    }
21595                }
21596            }
21597
21598            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21599                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21600            }
21601
21602            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21603                boolean printedSomething = false;
21604                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21605                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21606                        continue;
21607                    }
21608                    if (!printedSomething) {
21609                        if (dumpState.onTitlePrinted())
21610                            pw.println();
21611                        pw.println("Registered ContentProviders:");
21612                        printedSomething = true;
21613                    }
21614                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21615                    pw.print("    "); pw.println(p.toString());
21616                }
21617                printedSomething = false;
21618                for (Map.Entry<String, PackageParser.Provider> entry :
21619                        mProvidersByAuthority.entrySet()) {
21620                    PackageParser.Provider p = entry.getValue();
21621                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21622                        continue;
21623                    }
21624                    if (!printedSomething) {
21625                        if (dumpState.onTitlePrinted())
21626                            pw.println();
21627                        pw.println("ContentProvider Authorities:");
21628                        printedSomething = true;
21629                    }
21630                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21631                    pw.print("    "); pw.println(p.toString());
21632                    if (p.info != null && p.info.applicationInfo != null) {
21633                        final String appInfo = p.info.applicationInfo.toString();
21634                        pw.print("      applicationInfo="); pw.println(appInfo);
21635                    }
21636                }
21637            }
21638
21639            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21640                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21641            }
21642
21643            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21644                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21645            }
21646
21647            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21648                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21649            }
21650
21651            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21652                if (dumpState.onTitlePrinted()) pw.println();
21653                pw.println("Package Changes:");
21654                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21655                final int K = mChangedPackages.size();
21656                for (int i = 0; i < K; i++) {
21657                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21658                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21659                    final int N = changes.size();
21660                    if (N == 0) {
21661                        pw.print("    "); pw.println("No packages changed");
21662                    } else {
21663                        for (int j = 0; j < N; j++) {
21664                            final String pkgName = changes.valueAt(j);
21665                            final int sequenceNumber = changes.keyAt(j);
21666                            pw.print("    ");
21667                            pw.print("seq=");
21668                            pw.print(sequenceNumber);
21669                            pw.print(", package=");
21670                            pw.println(pkgName);
21671                        }
21672                    }
21673                }
21674            }
21675
21676            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21677                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21678            }
21679
21680            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21681                // XXX should handle packageName != null by dumping only install data that
21682                // the given package is involved with.
21683                if (dumpState.onTitlePrinted()) pw.println();
21684
21685                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21686                ipw.println();
21687                ipw.println("Frozen packages:");
21688                ipw.increaseIndent();
21689                if (mFrozenPackages.size() == 0) {
21690                    ipw.println("(none)");
21691                } else {
21692                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21693                        ipw.println(mFrozenPackages.valueAt(i));
21694                    }
21695                }
21696                ipw.decreaseIndent();
21697            }
21698
21699            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21700                if (dumpState.onTitlePrinted()) pw.println();
21701
21702                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21703                ipw.println();
21704                ipw.println("Loaded volumes:");
21705                ipw.increaseIndent();
21706                if (mLoadedVolumes.size() == 0) {
21707                    ipw.println("(none)");
21708                } else {
21709                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21710                        ipw.println(mLoadedVolumes.valueAt(i));
21711                    }
21712                }
21713                ipw.decreaseIndent();
21714            }
21715
21716            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21717                    && packageName == null) {
21718                if (dumpState.onTitlePrinted()) pw.println();
21719                pw.println("Service permissions:");
21720
21721                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21722                while (filterIterator.hasNext()) {
21723                    final ServiceIntentInfo info = filterIterator.next();
21724                    final ServiceInfo serviceInfo = info.service.info;
21725                    final String permission = serviceInfo.permission;
21726                    if (permission != null) {
21727                        pw.print("    ");
21728                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21729                        pw.print(": ");
21730                        pw.println(permission);
21731                    }
21732                }
21733            }
21734
21735            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21736                if (dumpState.onTitlePrinted()) pw.println();
21737                dumpDexoptStateLPr(pw, packageName);
21738            }
21739
21740            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21741                if (dumpState.onTitlePrinted()) pw.println();
21742                dumpCompilerStatsLPr(pw, packageName);
21743            }
21744
21745            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21746                if (dumpState.onTitlePrinted()) pw.println();
21747                mSettings.dumpReadMessagesLPr(pw, dumpState);
21748
21749                pw.println();
21750                pw.println("Package warning messages:");
21751                dumpCriticalInfo(pw, null);
21752            }
21753
21754            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21755                dumpCriticalInfo(pw, "msg,");
21756            }
21757        }
21758
21759        // PackageInstaller should be called outside of mPackages lock
21760        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21761            // XXX should handle packageName != null by dumping only install data that
21762            // the given package is involved with.
21763            if (dumpState.onTitlePrinted()) pw.println();
21764            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21765        }
21766    }
21767
21768    private void dumpProto(FileDescriptor fd) {
21769        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21770
21771        synchronized (mPackages) {
21772            final long requiredVerifierPackageToken =
21773                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21774            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21775            proto.write(
21776                    PackageServiceDumpProto.PackageShortProto.UID,
21777                    getPackageUid(
21778                            mRequiredVerifierPackage,
21779                            MATCH_DEBUG_TRIAGED_MISSING,
21780                            UserHandle.USER_SYSTEM));
21781            proto.end(requiredVerifierPackageToken);
21782
21783            if (mIntentFilterVerifierComponent != null) {
21784                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21785                final long verifierPackageToken =
21786                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21787                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21788                proto.write(
21789                        PackageServiceDumpProto.PackageShortProto.UID,
21790                        getPackageUid(
21791                                verifierPackageName,
21792                                MATCH_DEBUG_TRIAGED_MISSING,
21793                                UserHandle.USER_SYSTEM));
21794                proto.end(verifierPackageToken);
21795            }
21796
21797            dumpSharedLibrariesProto(proto);
21798            dumpFeaturesProto(proto);
21799            mSettings.dumpPackagesProto(proto);
21800            mSettings.dumpSharedUsersProto(proto);
21801            dumpCriticalInfo(proto);
21802        }
21803        proto.flush();
21804    }
21805
21806    private void dumpFeaturesProto(ProtoOutputStream proto) {
21807        synchronized (mAvailableFeatures) {
21808            final int count = mAvailableFeatures.size();
21809            for (int i = 0; i < count; i++) {
21810                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21811            }
21812        }
21813    }
21814
21815    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21816        final int count = mSharedLibraries.size();
21817        for (int i = 0; i < count; i++) {
21818            final String libName = mSharedLibraries.keyAt(i);
21819            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21820            if (versionedLib == null) {
21821                continue;
21822            }
21823            final int versionCount = versionedLib.size();
21824            for (int j = 0; j < versionCount; j++) {
21825                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21826                final long sharedLibraryToken =
21827                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21828                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21829                final boolean isJar = (libEntry.path != null);
21830                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21831                if (isJar) {
21832                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21833                } else {
21834                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21835                }
21836                proto.end(sharedLibraryToken);
21837            }
21838        }
21839    }
21840
21841    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21842        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21843        ipw.println();
21844        ipw.println("Dexopt state:");
21845        ipw.increaseIndent();
21846        Collection<PackageParser.Package> packages = null;
21847        if (packageName != null) {
21848            PackageParser.Package targetPackage = mPackages.get(packageName);
21849            if (targetPackage != null) {
21850                packages = Collections.singletonList(targetPackage);
21851            } else {
21852                ipw.println("Unable to find package: " + packageName);
21853                return;
21854            }
21855        } else {
21856            packages = mPackages.values();
21857        }
21858
21859        for (PackageParser.Package pkg : packages) {
21860            ipw.println("[" + pkg.packageName + "]");
21861            ipw.increaseIndent();
21862            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21863                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21864            ipw.decreaseIndent();
21865        }
21866    }
21867
21868    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21869        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21870        ipw.println();
21871        ipw.println("Compiler stats:");
21872        ipw.increaseIndent();
21873        Collection<PackageParser.Package> packages = null;
21874        if (packageName != null) {
21875            PackageParser.Package targetPackage = mPackages.get(packageName);
21876            if (targetPackage != null) {
21877                packages = Collections.singletonList(targetPackage);
21878            } else {
21879                ipw.println("Unable to find package: " + packageName);
21880                return;
21881            }
21882        } else {
21883            packages = mPackages.values();
21884        }
21885
21886        for (PackageParser.Package pkg : packages) {
21887            ipw.println("[" + pkg.packageName + "]");
21888            ipw.increaseIndent();
21889
21890            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21891            if (stats == null) {
21892                ipw.println("(No recorded stats)");
21893            } else {
21894                stats.dump(ipw);
21895            }
21896            ipw.decreaseIndent();
21897        }
21898    }
21899
21900    private String dumpDomainString(String packageName) {
21901        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21902                .getList();
21903        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21904
21905        ArraySet<String> result = new ArraySet<>();
21906        if (iviList.size() > 0) {
21907            for (IntentFilterVerificationInfo ivi : iviList) {
21908                for (String host : ivi.getDomains()) {
21909                    result.add(host);
21910                }
21911            }
21912        }
21913        if (filters != null && filters.size() > 0) {
21914            for (IntentFilter filter : filters) {
21915                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21916                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21917                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21918                    result.addAll(filter.getHostsList());
21919                }
21920            }
21921        }
21922
21923        StringBuilder sb = new StringBuilder(result.size() * 16);
21924        for (String domain : result) {
21925            if (sb.length() > 0) sb.append(" ");
21926            sb.append(domain);
21927        }
21928        return sb.toString();
21929    }
21930
21931    // ------- apps on sdcard specific code -------
21932    static final boolean DEBUG_SD_INSTALL = false;
21933
21934    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21935
21936    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21937
21938    private boolean mMediaMounted = false;
21939
21940    static String getEncryptKey() {
21941        try {
21942            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21943                    SD_ENCRYPTION_KEYSTORE_NAME);
21944            if (sdEncKey == null) {
21945                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21946                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21947                if (sdEncKey == null) {
21948                    Slog.e(TAG, "Failed to create encryption keys");
21949                    return null;
21950                }
21951            }
21952            return sdEncKey;
21953        } catch (NoSuchAlgorithmException nsae) {
21954            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21955            return null;
21956        } catch (IOException ioe) {
21957            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21958            return null;
21959        }
21960    }
21961
21962    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21963            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21964        final int size = infos.size();
21965        final String[] packageNames = new String[size];
21966        final int[] packageUids = new int[size];
21967        for (int i = 0; i < size; i++) {
21968            final ApplicationInfo info = infos.get(i);
21969            packageNames[i] = info.packageName;
21970            packageUids[i] = info.uid;
21971        }
21972        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21973                finishedReceiver);
21974    }
21975
21976    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21977            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21978        sendResourcesChangedBroadcast(mediaStatus, replacing,
21979                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21980    }
21981
21982    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21983            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21984        int size = pkgList.length;
21985        if (size > 0) {
21986            // Send broadcasts here
21987            Bundle extras = new Bundle();
21988            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21989            if (uidArr != null) {
21990                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21991            }
21992            if (replacing) {
21993                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21994            }
21995            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21996                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21997            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21998        }
21999    }
22000
22001    private void loadPrivatePackages(final VolumeInfo vol) {
22002        mHandler.post(new Runnable() {
22003            @Override
22004            public void run() {
22005                loadPrivatePackagesInner(vol);
22006            }
22007        });
22008    }
22009
22010    private void loadPrivatePackagesInner(VolumeInfo vol) {
22011        final String volumeUuid = vol.fsUuid;
22012        if (TextUtils.isEmpty(volumeUuid)) {
22013            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22014            return;
22015        }
22016
22017        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22018        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22019        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22020
22021        final VersionInfo ver;
22022        final List<PackageSetting> packages;
22023        synchronized (mPackages) {
22024            ver = mSettings.findOrCreateVersion(volumeUuid);
22025            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22026        }
22027
22028        for (PackageSetting ps : packages) {
22029            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22030            synchronized (mInstallLock) {
22031                final PackageParser.Package pkg;
22032                try {
22033                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22034                    loaded.add(pkg.applicationInfo);
22035
22036                } catch (PackageManagerException e) {
22037                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22038                }
22039
22040                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22041                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22042                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22043                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22044                }
22045            }
22046        }
22047
22048        // Reconcile app data for all started/unlocked users
22049        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22050        final UserManager um = mContext.getSystemService(UserManager.class);
22051        UserManagerInternal umInternal = getUserManagerInternal();
22052        for (UserInfo user : um.getUsers()) {
22053            final int flags;
22054            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22055                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22056            } else if (umInternal.isUserRunning(user.id)) {
22057                flags = StorageManager.FLAG_STORAGE_DE;
22058            } else {
22059                continue;
22060            }
22061
22062            try {
22063                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22064                synchronized (mInstallLock) {
22065                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22066                }
22067            } catch (IllegalStateException e) {
22068                // Device was probably ejected, and we'll process that event momentarily
22069                Slog.w(TAG, "Failed to prepare storage: " + e);
22070            }
22071        }
22072
22073        synchronized (mPackages) {
22074            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22075            if (sdkUpdated) {
22076                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22077                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22078            }
22079            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22080                    mPermissionCallback);
22081
22082            // Yay, everything is now upgraded
22083            ver.forceCurrent();
22084
22085            mSettings.writeLPr();
22086        }
22087
22088        for (PackageFreezer freezer : freezers) {
22089            freezer.close();
22090        }
22091
22092        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22093        sendResourcesChangedBroadcast(true, false, loaded, null);
22094        mLoadedVolumes.add(vol.getId());
22095    }
22096
22097    private void unloadPrivatePackages(final VolumeInfo vol) {
22098        mHandler.post(new Runnable() {
22099            @Override
22100            public void run() {
22101                unloadPrivatePackagesInner(vol);
22102            }
22103        });
22104    }
22105
22106    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22107        final String volumeUuid = vol.fsUuid;
22108        if (TextUtils.isEmpty(volumeUuid)) {
22109            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22110            return;
22111        }
22112
22113        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22114        synchronized (mInstallLock) {
22115        synchronized (mPackages) {
22116            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22117            for (PackageSetting ps : packages) {
22118                if (ps.pkg == null) continue;
22119
22120                final ApplicationInfo info = ps.pkg.applicationInfo;
22121                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22122                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22123
22124                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22125                        "unloadPrivatePackagesInner")) {
22126                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22127                            false, null)) {
22128                        unloaded.add(info);
22129                    } else {
22130                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22131                    }
22132                }
22133
22134                // Try very hard to release any references to this package
22135                // so we don't risk the system server being killed due to
22136                // open FDs
22137                AttributeCache.instance().removePackage(ps.name);
22138            }
22139
22140            mSettings.writeLPr();
22141        }
22142        }
22143
22144        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22145        sendResourcesChangedBroadcast(false, false, unloaded, null);
22146        mLoadedVolumes.remove(vol.getId());
22147
22148        // Try very hard to release any references to this path so we don't risk
22149        // the system server being killed due to open FDs
22150        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22151
22152        for (int i = 0; i < 3; i++) {
22153            System.gc();
22154            System.runFinalization();
22155        }
22156    }
22157
22158    private void assertPackageKnown(String volumeUuid, String packageName)
22159            throws PackageManagerException {
22160        synchronized (mPackages) {
22161            // Normalize package name to handle renamed packages
22162            packageName = normalizePackageNameLPr(packageName);
22163
22164            final PackageSetting ps = mSettings.mPackages.get(packageName);
22165            if (ps == null) {
22166                throw new PackageManagerException("Package " + packageName + " is unknown");
22167            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22168                throw new PackageManagerException(
22169                        "Package " + packageName + " found on unknown volume " + volumeUuid
22170                                + "; expected volume " + ps.volumeUuid);
22171            }
22172        }
22173    }
22174
22175    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22176            throws PackageManagerException {
22177        synchronized (mPackages) {
22178            // Normalize package name to handle renamed packages
22179            packageName = normalizePackageNameLPr(packageName);
22180
22181            final PackageSetting ps = mSettings.mPackages.get(packageName);
22182            if (ps == null) {
22183                throw new PackageManagerException("Package " + packageName + " is unknown");
22184            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22185                throw new PackageManagerException(
22186                        "Package " + packageName + " found on unknown volume " + volumeUuid
22187                                + "; expected volume " + ps.volumeUuid);
22188            } else if (!ps.getInstalled(userId)) {
22189                throw new PackageManagerException(
22190                        "Package " + packageName + " not installed for user " + userId);
22191            }
22192        }
22193    }
22194
22195    private List<String> collectAbsoluteCodePaths() {
22196        synchronized (mPackages) {
22197            List<String> codePaths = new ArrayList<>();
22198            final int packageCount = mSettings.mPackages.size();
22199            for (int i = 0; i < packageCount; i++) {
22200                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22201                codePaths.add(ps.codePath.getAbsolutePath());
22202            }
22203            return codePaths;
22204        }
22205    }
22206
22207    /**
22208     * Examine all apps present on given mounted volume, and destroy apps that
22209     * aren't expected, either due to uninstallation or reinstallation on
22210     * another volume.
22211     */
22212    private void reconcileApps(String volumeUuid) {
22213        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22214        List<File> filesToDelete = null;
22215
22216        final File[] files = FileUtils.listFilesOrEmpty(
22217                Environment.getDataAppDirectory(volumeUuid));
22218        for (File file : files) {
22219            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22220                    && !PackageInstallerService.isStageName(file.getName());
22221            if (!isPackage) {
22222                // Ignore entries which are not packages
22223                continue;
22224            }
22225
22226            String absolutePath = file.getAbsolutePath();
22227
22228            boolean pathValid = false;
22229            final int absoluteCodePathCount = absoluteCodePaths.size();
22230            for (int i = 0; i < absoluteCodePathCount; i++) {
22231                String absoluteCodePath = absoluteCodePaths.get(i);
22232                if (absolutePath.startsWith(absoluteCodePath)) {
22233                    pathValid = true;
22234                    break;
22235                }
22236            }
22237
22238            if (!pathValid) {
22239                if (filesToDelete == null) {
22240                    filesToDelete = new ArrayList<>();
22241                }
22242                filesToDelete.add(file);
22243            }
22244        }
22245
22246        if (filesToDelete != null) {
22247            final int fileToDeleteCount = filesToDelete.size();
22248            for (int i = 0; i < fileToDeleteCount; i++) {
22249                File fileToDelete = filesToDelete.get(i);
22250                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22251                synchronized (mInstallLock) {
22252                    removeCodePathLI(fileToDelete);
22253                }
22254            }
22255        }
22256    }
22257
22258    /**
22259     * Reconcile all app data for the given user.
22260     * <p>
22261     * Verifies that directories exist and that ownership and labeling is
22262     * correct for all installed apps on all mounted volumes.
22263     */
22264    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22265        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22266        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22267            final String volumeUuid = vol.getFsUuid();
22268            synchronized (mInstallLock) {
22269                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22270            }
22271        }
22272    }
22273
22274    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22275            boolean migrateAppData) {
22276        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22277    }
22278
22279    /**
22280     * Reconcile all app data on given mounted volume.
22281     * <p>
22282     * Destroys app data that isn't expected, either due to uninstallation or
22283     * reinstallation on another volume.
22284     * <p>
22285     * Verifies that directories exist and that ownership and labeling is
22286     * correct for all installed apps.
22287     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22288     */
22289    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22290            boolean migrateAppData, boolean onlyCoreApps) {
22291        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22292                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22293        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22294
22295        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22296        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22297
22298        // First look for stale data that doesn't belong, and check if things
22299        // have changed since we did our last restorecon
22300        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22301            if (StorageManager.isFileEncryptedNativeOrEmulated()
22302                    && !StorageManager.isUserKeyUnlocked(userId)) {
22303                throw new RuntimeException(
22304                        "Yikes, someone asked us to reconcile CE storage while " + userId
22305                                + " was still locked; this would have caused massive data loss!");
22306            }
22307
22308            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22309            for (File file : files) {
22310                final String packageName = file.getName();
22311                try {
22312                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22313                } catch (PackageManagerException e) {
22314                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22315                    try {
22316                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22317                                StorageManager.FLAG_STORAGE_CE, 0);
22318                    } catch (InstallerException e2) {
22319                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22320                    }
22321                }
22322            }
22323        }
22324        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22325            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22326            for (File file : files) {
22327                final String packageName = file.getName();
22328                try {
22329                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22330                } catch (PackageManagerException e) {
22331                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22332                    try {
22333                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22334                                StorageManager.FLAG_STORAGE_DE, 0);
22335                    } catch (InstallerException e2) {
22336                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22337                    }
22338                }
22339            }
22340        }
22341
22342        // Ensure that data directories are ready to roll for all packages
22343        // installed for this volume and user
22344        final List<PackageSetting> packages;
22345        synchronized (mPackages) {
22346            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22347        }
22348        int preparedCount = 0;
22349        for (PackageSetting ps : packages) {
22350            final String packageName = ps.name;
22351            if (ps.pkg == null) {
22352                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22353                // TODO: might be due to legacy ASEC apps; we should circle back
22354                // and reconcile again once they're scanned
22355                continue;
22356            }
22357            // Skip non-core apps if requested
22358            if (onlyCoreApps && !ps.pkg.coreApp) {
22359                result.add(packageName);
22360                continue;
22361            }
22362
22363            if (ps.getInstalled(userId)) {
22364                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22365                preparedCount++;
22366            }
22367        }
22368
22369        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22370        return result;
22371    }
22372
22373    /**
22374     * Prepare app data for the given app just after it was installed or
22375     * upgraded. This method carefully only touches users that it's installed
22376     * for, and it forces a restorecon to handle any seinfo changes.
22377     * <p>
22378     * Verifies that directories exist and that ownership and labeling is
22379     * correct for all installed apps. If there is an ownership mismatch, it
22380     * will try recovering system apps by wiping data; third-party app data is
22381     * left intact.
22382     * <p>
22383     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22384     */
22385    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22386        final PackageSetting ps;
22387        synchronized (mPackages) {
22388            ps = mSettings.mPackages.get(pkg.packageName);
22389            mSettings.writeKernelMappingLPr(ps);
22390        }
22391
22392        final UserManager um = mContext.getSystemService(UserManager.class);
22393        UserManagerInternal umInternal = getUserManagerInternal();
22394        for (UserInfo user : um.getUsers()) {
22395            final int flags;
22396            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22397                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22398            } else if (umInternal.isUserRunning(user.id)) {
22399                flags = StorageManager.FLAG_STORAGE_DE;
22400            } else {
22401                continue;
22402            }
22403
22404            if (ps.getInstalled(user.id)) {
22405                // TODO: when user data is locked, mark that we're still dirty
22406                prepareAppDataLIF(pkg, user.id, flags);
22407            }
22408        }
22409    }
22410
22411    /**
22412     * Prepare app data for the given app.
22413     * <p>
22414     * Verifies that directories exist and that ownership and labeling is
22415     * correct for all installed apps. If there is an ownership mismatch, this
22416     * will try recovering system apps by wiping data; third-party app data is
22417     * left intact.
22418     */
22419    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22420        if (pkg == null) {
22421            Slog.wtf(TAG, "Package was null!", new Throwable());
22422            return;
22423        }
22424        prepareAppDataLeafLIF(pkg, userId, flags);
22425        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22426        for (int i = 0; i < childCount; i++) {
22427            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22428        }
22429    }
22430
22431    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22432            boolean maybeMigrateAppData) {
22433        prepareAppDataLIF(pkg, userId, flags);
22434
22435        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22436            // We may have just shuffled around app data directories, so
22437            // prepare them one more time
22438            prepareAppDataLIF(pkg, userId, flags);
22439        }
22440    }
22441
22442    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22443        if (DEBUG_APP_DATA) {
22444            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22445                    + Integer.toHexString(flags));
22446        }
22447
22448        final PackageSetting ps;
22449        synchronized (mPackages) {
22450            ps = mSettings.mPackages.get(pkg.packageName);
22451        }
22452        final String volumeUuid = pkg.volumeUuid;
22453        final String packageName = pkg.packageName;
22454        final ApplicationInfo app = (ps == null)
22455                ? pkg.applicationInfo
22456                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22457
22458        final int appId = UserHandle.getAppId(app.uid);
22459
22460        Preconditions.checkNotNull(app.seInfo);
22461
22462        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22463        long ceDataInode = -1;
22464        try {
22465            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22466                    appId, seInfo, app.targetSdkVersion);
22467        } catch (InstallerException e) {
22468            if (app.isSystemApp()) {
22469                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22470                        + ", but trying to recover: " + e);
22471                destroyAppDataLeafLIF(pkg, userId, flags);
22472                try {
22473                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22474                            appId, seInfo, app.targetSdkVersion);
22475                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22476                } catch (InstallerException e2) {
22477                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22478                }
22479            } else {
22480                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22481            }
22482        }
22483        // Prepare the application profiles only for upgrades and first boot (so that we don't
22484        // repeat the same operation at each boot).
22485        // We only have to cover the upgrade and first boot here because for app installs we
22486        // prepare the profiles before invoking dexopt (in installPackageLI).
22487        //
22488        // We also have to cover non system users because we do not call the usual install package
22489        // methods for them.
22490        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22491            mArtManagerService.prepareAppProfiles(pkg, userId);
22492        }
22493
22494        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22495            // TODO: mark this structure as dirty so we persist it!
22496            synchronized (mPackages) {
22497                if (ps != null) {
22498                    ps.setCeDataInode(ceDataInode, userId);
22499                }
22500            }
22501        }
22502
22503        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22504    }
22505
22506    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22507        if (pkg == null) {
22508            Slog.wtf(TAG, "Package was null!", new Throwable());
22509            return;
22510        }
22511        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22513        for (int i = 0; i < childCount; i++) {
22514            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22515        }
22516    }
22517
22518    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22519        final String volumeUuid = pkg.volumeUuid;
22520        final String packageName = pkg.packageName;
22521        final ApplicationInfo app = pkg.applicationInfo;
22522
22523        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22524            // Create a native library symlink only if we have native libraries
22525            // and if the native libraries are 32 bit libraries. We do not provide
22526            // this symlink for 64 bit libraries.
22527            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22528                final String nativeLibPath = app.nativeLibraryDir;
22529                try {
22530                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22531                            nativeLibPath, userId);
22532                } catch (InstallerException e) {
22533                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22534                }
22535            }
22536        }
22537    }
22538
22539    /**
22540     * For system apps on non-FBE devices, this method migrates any existing
22541     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22542     * requested by the app.
22543     */
22544    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22545        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22546                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22547            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22548                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22549            try {
22550                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22551                        storageTarget);
22552            } catch (InstallerException e) {
22553                logCriticalInfo(Log.WARN,
22554                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22555            }
22556            return true;
22557        } else {
22558            return false;
22559        }
22560    }
22561
22562    public PackageFreezer freezePackage(String packageName, String killReason) {
22563        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22564    }
22565
22566    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22567        return new PackageFreezer(packageName, userId, killReason);
22568    }
22569
22570    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22571            String killReason) {
22572        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22573    }
22574
22575    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22576            String killReason) {
22577        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22578            return new PackageFreezer();
22579        } else {
22580            return freezePackage(packageName, userId, killReason);
22581        }
22582    }
22583
22584    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22585            String killReason) {
22586        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22587    }
22588
22589    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22590            String killReason) {
22591        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22592            return new PackageFreezer();
22593        } else {
22594            return freezePackage(packageName, userId, killReason);
22595        }
22596    }
22597
22598    /**
22599     * Class that freezes and kills the given package upon creation, and
22600     * unfreezes it upon closing. This is typically used when doing surgery on
22601     * app code/data to prevent the app from running while you're working.
22602     */
22603    private class PackageFreezer implements AutoCloseable {
22604        private final String mPackageName;
22605        private final PackageFreezer[] mChildren;
22606
22607        private final boolean mWeFroze;
22608
22609        private final AtomicBoolean mClosed = new AtomicBoolean();
22610        private final CloseGuard mCloseGuard = CloseGuard.get();
22611
22612        /**
22613         * Create and return a stub freezer that doesn't actually do anything,
22614         * typically used when someone requested
22615         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22616         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22617         */
22618        public PackageFreezer() {
22619            mPackageName = null;
22620            mChildren = null;
22621            mWeFroze = false;
22622            mCloseGuard.open("close");
22623        }
22624
22625        public PackageFreezer(String packageName, int userId, String killReason) {
22626            synchronized (mPackages) {
22627                mPackageName = packageName;
22628                mWeFroze = mFrozenPackages.add(mPackageName);
22629
22630                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22631                if (ps != null) {
22632                    killApplication(ps.name, ps.appId, userId, killReason);
22633                }
22634
22635                final PackageParser.Package p = mPackages.get(packageName);
22636                if (p != null && p.childPackages != null) {
22637                    final int N = p.childPackages.size();
22638                    mChildren = new PackageFreezer[N];
22639                    for (int i = 0; i < N; i++) {
22640                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22641                                userId, killReason);
22642                    }
22643                } else {
22644                    mChildren = null;
22645                }
22646            }
22647            mCloseGuard.open("close");
22648        }
22649
22650        @Override
22651        protected void finalize() throws Throwable {
22652            try {
22653                if (mCloseGuard != null) {
22654                    mCloseGuard.warnIfOpen();
22655                }
22656
22657                close();
22658            } finally {
22659                super.finalize();
22660            }
22661        }
22662
22663        @Override
22664        public void close() {
22665            mCloseGuard.close();
22666            if (mClosed.compareAndSet(false, true)) {
22667                synchronized (mPackages) {
22668                    if (mWeFroze) {
22669                        mFrozenPackages.remove(mPackageName);
22670                    }
22671
22672                    if (mChildren != null) {
22673                        for (PackageFreezer freezer : mChildren) {
22674                            freezer.close();
22675                        }
22676                    }
22677                }
22678            }
22679        }
22680    }
22681
22682    /**
22683     * Verify that given package is currently frozen.
22684     */
22685    private void checkPackageFrozen(String packageName) {
22686        synchronized (mPackages) {
22687            if (!mFrozenPackages.contains(packageName)) {
22688                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22689            }
22690        }
22691    }
22692
22693    @Override
22694    public int movePackage(final String packageName, final String volumeUuid) {
22695        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22696
22697        final int callingUid = Binder.getCallingUid();
22698        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22699        final int moveId = mNextMoveId.getAndIncrement();
22700        mHandler.post(new Runnable() {
22701            @Override
22702            public void run() {
22703                try {
22704                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22705                } catch (PackageManagerException e) {
22706                    Slog.w(TAG, "Failed to move " + packageName, e);
22707                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22708                }
22709            }
22710        });
22711        return moveId;
22712    }
22713
22714    private void movePackageInternal(final String packageName, final String volumeUuid,
22715            final int moveId, final int callingUid, UserHandle user)
22716                    throws PackageManagerException {
22717        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22718        final PackageManager pm = mContext.getPackageManager();
22719
22720        final boolean currentAsec;
22721        final String currentVolumeUuid;
22722        final File codeFile;
22723        final String installerPackageName;
22724        final String packageAbiOverride;
22725        final int appId;
22726        final String seinfo;
22727        final String label;
22728        final int targetSdkVersion;
22729        final PackageFreezer freezer;
22730        final int[] installedUserIds;
22731
22732        // reader
22733        synchronized (mPackages) {
22734            final PackageParser.Package pkg = mPackages.get(packageName);
22735            final PackageSetting ps = mSettings.mPackages.get(packageName);
22736            if (pkg == null
22737                    || ps == null
22738                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22739                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22740            }
22741            if (pkg.applicationInfo.isSystemApp()) {
22742                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22743                        "Cannot move system application");
22744            }
22745
22746            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22747            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22748                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22749            if (isInternalStorage && !allow3rdPartyOnInternal) {
22750                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22751                        "3rd party apps are not allowed on internal storage");
22752            }
22753
22754            if (pkg.applicationInfo.isExternalAsec()) {
22755                currentAsec = true;
22756                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22757            } else if (pkg.applicationInfo.isForwardLocked()) {
22758                currentAsec = true;
22759                currentVolumeUuid = "forward_locked";
22760            } else {
22761                currentAsec = false;
22762                currentVolumeUuid = ps.volumeUuid;
22763
22764                final File probe = new File(pkg.codePath);
22765                final File probeOat = new File(probe, "oat");
22766                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22767                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22768                            "Move only supported for modern cluster style installs");
22769                }
22770            }
22771
22772            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22773                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22774                        "Package already moved to " + volumeUuid);
22775            }
22776            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22777                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22778                        "Device admin cannot be moved");
22779            }
22780
22781            if (mFrozenPackages.contains(packageName)) {
22782                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22783                        "Failed to move already frozen package");
22784            }
22785
22786            codeFile = new File(pkg.codePath);
22787            installerPackageName = ps.installerPackageName;
22788            packageAbiOverride = ps.cpuAbiOverrideString;
22789            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22790            seinfo = pkg.applicationInfo.seInfo;
22791            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22792            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22793            freezer = freezePackage(packageName, "movePackageInternal");
22794            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22795        }
22796
22797        final Bundle extras = new Bundle();
22798        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22799        extras.putString(Intent.EXTRA_TITLE, label);
22800        mMoveCallbacks.notifyCreated(moveId, extras);
22801
22802        int installFlags;
22803        final boolean moveCompleteApp;
22804        final File measurePath;
22805
22806        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22807            installFlags = INSTALL_INTERNAL;
22808            moveCompleteApp = !currentAsec;
22809            measurePath = Environment.getDataAppDirectory(volumeUuid);
22810        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22811            installFlags = INSTALL_EXTERNAL;
22812            moveCompleteApp = false;
22813            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22814        } else {
22815            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22816            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22817                    || !volume.isMountedWritable()) {
22818                freezer.close();
22819                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22820                        "Move location not mounted private volume");
22821            }
22822
22823            Preconditions.checkState(!currentAsec);
22824
22825            installFlags = INSTALL_INTERNAL;
22826            moveCompleteApp = true;
22827            measurePath = Environment.getDataAppDirectory(volumeUuid);
22828        }
22829
22830        // If we're moving app data around, we need all the users unlocked
22831        if (moveCompleteApp) {
22832            for (int userId : installedUserIds) {
22833                if (StorageManager.isFileEncryptedNativeOrEmulated()
22834                        && !StorageManager.isUserKeyUnlocked(userId)) {
22835                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22836                            "User " + userId + " must be unlocked");
22837                }
22838            }
22839        }
22840
22841        final PackageStats stats = new PackageStats(null, -1);
22842        synchronized (mInstaller) {
22843            for (int userId : installedUserIds) {
22844                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22845                    freezer.close();
22846                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22847                            "Failed to measure package size");
22848                }
22849            }
22850        }
22851
22852        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22853                + stats.dataSize);
22854
22855        final long startFreeBytes = measurePath.getUsableSpace();
22856        final long sizeBytes;
22857        if (moveCompleteApp) {
22858            sizeBytes = stats.codeSize + stats.dataSize;
22859        } else {
22860            sizeBytes = stats.codeSize;
22861        }
22862
22863        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22864            freezer.close();
22865            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22866                    "Not enough free space to move");
22867        }
22868
22869        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22870
22871        final CountDownLatch installedLatch = new CountDownLatch(1);
22872        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22873            @Override
22874            public void onUserActionRequired(Intent intent) throws RemoteException {
22875                throw new IllegalStateException();
22876            }
22877
22878            @Override
22879            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22880                    Bundle extras) throws RemoteException {
22881                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22882                        + PackageManager.installStatusToString(returnCode, msg));
22883
22884                installedLatch.countDown();
22885                freezer.close();
22886
22887                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22888                switch (status) {
22889                    case PackageInstaller.STATUS_SUCCESS:
22890                        mMoveCallbacks.notifyStatusChanged(moveId,
22891                                PackageManager.MOVE_SUCCEEDED);
22892                        break;
22893                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22894                        mMoveCallbacks.notifyStatusChanged(moveId,
22895                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22896                        break;
22897                    default:
22898                        mMoveCallbacks.notifyStatusChanged(moveId,
22899                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22900                        break;
22901                }
22902            }
22903        };
22904
22905        final MoveInfo move;
22906        if (moveCompleteApp) {
22907            // Kick off a thread to report progress estimates
22908            new Thread() {
22909                @Override
22910                public void run() {
22911                    while (true) {
22912                        try {
22913                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22914                                break;
22915                            }
22916                        } catch (InterruptedException ignored) {
22917                        }
22918
22919                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22920                        final int progress = 10 + (int) MathUtils.constrain(
22921                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22922                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22923                    }
22924                }
22925            }.start();
22926
22927            final String dataAppName = codeFile.getName();
22928            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22929                    dataAppName, appId, seinfo, targetSdkVersion);
22930        } else {
22931            move = null;
22932        }
22933
22934        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22935
22936        final Message msg = mHandler.obtainMessage(INIT_COPY);
22937        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22938        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22939                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22940                packageAbiOverride, null /*grantedPermissions*/,
22941                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22942        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22943        msg.obj = params;
22944
22945        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22946                System.identityHashCode(msg.obj));
22947        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22948                System.identityHashCode(msg.obj));
22949
22950        mHandler.sendMessage(msg);
22951    }
22952
22953    @Override
22954    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22955        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22956
22957        final int realMoveId = mNextMoveId.getAndIncrement();
22958        final Bundle extras = new Bundle();
22959        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22960        mMoveCallbacks.notifyCreated(realMoveId, extras);
22961
22962        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22963            @Override
22964            public void onCreated(int moveId, Bundle extras) {
22965                // Ignored
22966            }
22967
22968            @Override
22969            public void onStatusChanged(int moveId, int status, long estMillis) {
22970                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22971            }
22972        };
22973
22974        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22975        storage.setPrimaryStorageUuid(volumeUuid, callback);
22976        return realMoveId;
22977    }
22978
22979    @Override
22980    public int getMoveStatus(int moveId) {
22981        mContext.enforceCallingOrSelfPermission(
22982                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22983        return mMoveCallbacks.mLastStatus.get(moveId);
22984    }
22985
22986    @Override
22987    public void registerMoveCallback(IPackageMoveObserver callback) {
22988        mContext.enforceCallingOrSelfPermission(
22989                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22990        mMoveCallbacks.register(callback);
22991    }
22992
22993    @Override
22994    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22995        mContext.enforceCallingOrSelfPermission(
22996                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22997        mMoveCallbacks.unregister(callback);
22998    }
22999
23000    @Override
23001    public boolean setInstallLocation(int loc) {
23002        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23003                null);
23004        if (getInstallLocation() == loc) {
23005            return true;
23006        }
23007        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23008                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23009            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23010                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23011            return true;
23012        }
23013        return false;
23014   }
23015
23016    @Override
23017    public int getInstallLocation() {
23018        // allow instant app access
23019        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23020                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23021                PackageHelper.APP_INSTALL_AUTO);
23022    }
23023
23024    /** Called by UserManagerService */
23025    void cleanUpUser(UserManagerService userManager, int userHandle) {
23026        synchronized (mPackages) {
23027            mDirtyUsers.remove(userHandle);
23028            mUserNeedsBadging.delete(userHandle);
23029            mSettings.removeUserLPw(userHandle);
23030            mPendingBroadcasts.remove(userHandle);
23031            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23032            removeUnusedPackagesLPw(userManager, userHandle);
23033        }
23034    }
23035
23036    /**
23037     * We're removing userHandle and would like to remove any downloaded packages
23038     * that are no longer in use by any other user.
23039     * @param userHandle the user being removed
23040     */
23041    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23042        final boolean DEBUG_CLEAN_APKS = false;
23043        int [] users = userManager.getUserIds();
23044        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23045        while (psit.hasNext()) {
23046            PackageSetting ps = psit.next();
23047            if (ps.pkg == null) {
23048                continue;
23049            }
23050            final String packageName = ps.pkg.packageName;
23051            // Skip over if system app
23052            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23053                continue;
23054            }
23055            if (DEBUG_CLEAN_APKS) {
23056                Slog.i(TAG, "Checking package " + packageName);
23057            }
23058            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23059            if (keep) {
23060                if (DEBUG_CLEAN_APKS) {
23061                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23062                }
23063            } else {
23064                for (int i = 0; i < users.length; i++) {
23065                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23066                        keep = true;
23067                        if (DEBUG_CLEAN_APKS) {
23068                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23069                                    + users[i]);
23070                        }
23071                        break;
23072                    }
23073                }
23074            }
23075            if (!keep) {
23076                if (DEBUG_CLEAN_APKS) {
23077                    Slog.i(TAG, "  Removing package " + packageName);
23078                }
23079                mHandler.post(new Runnable() {
23080                    public void run() {
23081                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23082                                userHandle, 0);
23083                    } //end run
23084                });
23085            }
23086        }
23087    }
23088
23089    /** Called by UserManagerService */
23090    void createNewUser(int userId, String[] disallowedPackages) {
23091        synchronized (mInstallLock) {
23092            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23093        }
23094        synchronized (mPackages) {
23095            scheduleWritePackageRestrictionsLocked(userId);
23096            scheduleWritePackageListLocked(userId);
23097            applyFactoryDefaultBrowserLPw(userId);
23098            primeDomainVerificationsLPw(userId);
23099        }
23100    }
23101
23102    void onNewUserCreated(final int userId) {
23103        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23104        synchronized(mPackages) {
23105            // If permission review for legacy apps is required, we represent
23106            // dagerous permissions for such apps as always granted runtime
23107            // permissions to keep per user flag state whether review is needed.
23108            // Hence, if a new user is added we have to propagate dangerous
23109            // permission grants for these legacy apps.
23110            if (mSettings.mPermissions.mPermissionReviewRequired) {
23111// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23112                mPermissionManager.updateAllPermissions(
23113                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23114                        mPermissionCallback);
23115            }
23116        }
23117    }
23118
23119    @Override
23120    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23121        mContext.enforceCallingOrSelfPermission(
23122                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23123                "Only package verification agents can read the verifier device identity");
23124
23125        synchronized (mPackages) {
23126            return mSettings.getVerifierDeviceIdentityLPw();
23127        }
23128    }
23129
23130    @Override
23131    public void setPermissionEnforced(String permission, boolean enforced) {
23132        // TODO: Now that we no longer change GID for storage, this should to away.
23133        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23134                "setPermissionEnforced");
23135        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23136            synchronized (mPackages) {
23137                if (mSettings.mReadExternalStorageEnforced == null
23138                        || mSettings.mReadExternalStorageEnforced != enforced) {
23139                    mSettings.mReadExternalStorageEnforced =
23140                            enforced ? Boolean.TRUE : Boolean.FALSE;
23141                    mSettings.writeLPr();
23142                }
23143            }
23144            // kill any non-foreground processes so we restart them and
23145            // grant/revoke the GID.
23146            final IActivityManager am = ActivityManager.getService();
23147            if (am != null) {
23148                final long token = Binder.clearCallingIdentity();
23149                try {
23150                    am.killProcessesBelowForeground("setPermissionEnforcement");
23151                } catch (RemoteException e) {
23152                } finally {
23153                    Binder.restoreCallingIdentity(token);
23154                }
23155            }
23156        } else {
23157            throw new IllegalArgumentException("No selective enforcement for " + permission);
23158        }
23159    }
23160
23161    @Override
23162    @Deprecated
23163    public boolean isPermissionEnforced(String permission) {
23164        // allow instant applications
23165        return true;
23166    }
23167
23168    @Override
23169    public boolean isStorageLow() {
23170        // allow instant applications
23171        final long token = Binder.clearCallingIdentity();
23172        try {
23173            final DeviceStorageMonitorInternal
23174                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23175            if (dsm != null) {
23176                return dsm.isMemoryLow();
23177            } else {
23178                return false;
23179            }
23180        } finally {
23181            Binder.restoreCallingIdentity(token);
23182        }
23183    }
23184
23185    @Override
23186    public IPackageInstaller getPackageInstaller() {
23187        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23188            return null;
23189        }
23190        return mInstallerService;
23191    }
23192
23193    @Override
23194    public IArtManager getArtManager() {
23195        return mArtManagerService;
23196    }
23197
23198    private boolean userNeedsBadging(int userId) {
23199        int index = mUserNeedsBadging.indexOfKey(userId);
23200        if (index < 0) {
23201            final UserInfo userInfo;
23202            final long token = Binder.clearCallingIdentity();
23203            try {
23204                userInfo = sUserManager.getUserInfo(userId);
23205            } finally {
23206                Binder.restoreCallingIdentity(token);
23207            }
23208            final boolean b;
23209            if (userInfo != null && userInfo.isManagedProfile()) {
23210                b = true;
23211            } else {
23212                b = false;
23213            }
23214            mUserNeedsBadging.put(userId, b);
23215            return b;
23216        }
23217        return mUserNeedsBadging.valueAt(index);
23218    }
23219
23220    @Override
23221    public KeySet getKeySetByAlias(String packageName, String alias) {
23222        if (packageName == null || alias == null) {
23223            return null;
23224        }
23225        synchronized(mPackages) {
23226            final PackageParser.Package pkg = mPackages.get(packageName);
23227            if (pkg == null) {
23228                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23229                throw new IllegalArgumentException("Unknown package: " + packageName);
23230            }
23231            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23232            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23233                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23234                throw new IllegalArgumentException("Unknown package: " + packageName);
23235            }
23236            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23237            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23238        }
23239    }
23240
23241    @Override
23242    public KeySet getSigningKeySet(String packageName) {
23243        if (packageName == null) {
23244            return null;
23245        }
23246        synchronized(mPackages) {
23247            final int callingUid = Binder.getCallingUid();
23248            final int callingUserId = UserHandle.getUserId(callingUid);
23249            final PackageParser.Package pkg = mPackages.get(packageName);
23250            if (pkg == null) {
23251                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23252                throw new IllegalArgumentException("Unknown package: " + packageName);
23253            }
23254            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23255            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23256                // filter and pretend the package doesn't exist
23257                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23258                        + ", uid:" + callingUid);
23259                throw new IllegalArgumentException("Unknown package: " + packageName);
23260            }
23261            if (pkg.applicationInfo.uid != callingUid
23262                    && Process.SYSTEM_UID != callingUid) {
23263                throw new SecurityException("May not access signing KeySet of other apps.");
23264            }
23265            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23266            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23267        }
23268    }
23269
23270    @Override
23271    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23272        final int callingUid = Binder.getCallingUid();
23273        if (getInstantAppPackageName(callingUid) != null) {
23274            return false;
23275        }
23276        if (packageName == null || ks == null) {
23277            return false;
23278        }
23279        synchronized(mPackages) {
23280            final PackageParser.Package pkg = mPackages.get(packageName);
23281            if (pkg == null
23282                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23283                            UserHandle.getUserId(callingUid))) {
23284                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23285                throw new IllegalArgumentException("Unknown package: " + packageName);
23286            }
23287            IBinder ksh = ks.getToken();
23288            if (ksh instanceof KeySetHandle) {
23289                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23290                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23291            }
23292            return false;
23293        }
23294    }
23295
23296    @Override
23297    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23298        final int callingUid = Binder.getCallingUid();
23299        if (getInstantAppPackageName(callingUid) != null) {
23300            return false;
23301        }
23302        if (packageName == null || ks == null) {
23303            return false;
23304        }
23305        synchronized(mPackages) {
23306            final PackageParser.Package pkg = mPackages.get(packageName);
23307            if (pkg == null
23308                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23309                            UserHandle.getUserId(callingUid))) {
23310                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23311                throw new IllegalArgumentException("Unknown package: " + packageName);
23312            }
23313            IBinder ksh = ks.getToken();
23314            if (ksh instanceof KeySetHandle) {
23315                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23316                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23317            }
23318            return false;
23319        }
23320    }
23321
23322    private void deletePackageIfUnusedLPr(final String packageName) {
23323        PackageSetting ps = mSettings.mPackages.get(packageName);
23324        if (ps == null) {
23325            return;
23326        }
23327        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23328            // TODO Implement atomic delete if package is unused
23329            // It is currently possible that the package will be deleted even if it is installed
23330            // after this method returns.
23331            mHandler.post(new Runnable() {
23332                public void run() {
23333                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23334                            0, PackageManager.DELETE_ALL_USERS);
23335                }
23336            });
23337        }
23338    }
23339
23340    /**
23341     * Check and throw if the given before/after packages would be considered a
23342     * downgrade.
23343     */
23344    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23345            throws PackageManagerException {
23346        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23347            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23348                    "Update version code " + after.versionCode + " is older than current "
23349                    + before.getLongVersionCode());
23350        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23351            if (after.baseRevisionCode < before.baseRevisionCode) {
23352                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23353                        "Update base revision code " + after.baseRevisionCode
23354                        + " is older than current " + before.baseRevisionCode);
23355            }
23356
23357            if (!ArrayUtils.isEmpty(after.splitNames)) {
23358                for (int i = 0; i < after.splitNames.length; i++) {
23359                    final String splitName = after.splitNames[i];
23360                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23361                    if (j != -1) {
23362                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23363                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23364                                    "Update split " + splitName + " revision code "
23365                                    + after.splitRevisionCodes[i] + " is older than current "
23366                                    + before.splitRevisionCodes[j]);
23367                        }
23368                    }
23369                }
23370            }
23371        }
23372    }
23373
23374    private static class MoveCallbacks extends Handler {
23375        private static final int MSG_CREATED = 1;
23376        private static final int MSG_STATUS_CHANGED = 2;
23377
23378        private final RemoteCallbackList<IPackageMoveObserver>
23379                mCallbacks = new RemoteCallbackList<>();
23380
23381        private final SparseIntArray mLastStatus = new SparseIntArray();
23382
23383        public MoveCallbacks(Looper looper) {
23384            super(looper);
23385        }
23386
23387        public void register(IPackageMoveObserver callback) {
23388            mCallbacks.register(callback);
23389        }
23390
23391        public void unregister(IPackageMoveObserver callback) {
23392            mCallbacks.unregister(callback);
23393        }
23394
23395        @Override
23396        public void handleMessage(Message msg) {
23397            final SomeArgs args = (SomeArgs) msg.obj;
23398            final int n = mCallbacks.beginBroadcast();
23399            for (int i = 0; i < n; i++) {
23400                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23401                try {
23402                    invokeCallback(callback, msg.what, args);
23403                } catch (RemoteException ignored) {
23404                }
23405            }
23406            mCallbacks.finishBroadcast();
23407            args.recycle();
23408        }
23409
23410        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23411                throws RemoteException {
23412            switch (what) {
23413                case MSG_CREATED: {
23414                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23415                    break;
23416                }
23417                case MSG_STATUS_CHANGED: {
23418                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23419                    break;
23420                }
23421            }
23422        }
23423
23424        private void notifyCreated(int moveId, Bundle extras) {
23425            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23426
23427            final SomeArgs args = SomeArgs.obtain();
23428            args.argi1 = moveId;
23429            args.arg2 = extras;
23430            obtainMessage(MSG_CREATED, args).sendToTarget();
23431        }
23432
23433        private void notifyStatusChanged(int moveId, int status) {
23434            notifyStatusChanged(moveId, status, -1);
23435        }
23436
23437        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23438            Slog.v(TAG, "Move " + moveId + " status " + status);
23439
23440            final SomeArgs args = SomeArgs.obtain();
23441            args.argi1 = moveId;
23442            args.argi2 = status;
23443            args.arg3 = estMillis;
23444            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23445
23446            synchronized (mLastStatus) {
23447                mLastStatus.put(moveId, status);
23448            }
23449        }
23450    }
23451
23452    private final static class OnPermissionChangeListeners extends Handler {
23453        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23454
23455        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23456                new RemoteCallbackList<>();
23457
23458        public OnPermissionChangeListeners(Looper looper) {
23459            super(looper);
23460        }
23461
23462        @Override
23463        public void handleMessage(Message msg) {
23464            switch (msg.what) {
23465                case MSG_ON_PERMISSIONS_CHANGED: {
23466                    final int uid = msg.arg1;
23467                    handleOnPermissionsChanged(uid);
23468                } break;
23469            }
23470        }
23471
23472        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23473            mPermissionListeners.register(listener);
23474
23475        }
23476
23477        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23478            mPermissionListeners.unregister(listener);
23479        }
23480
23481        public void onPermissionsChanged(int uid) {
23482            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23483                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23484            }
23485        }
23486
23487        private void handleOnPermissionsChanged(int uid) {
23488            final int count = mPermissionListeners.beginBroadcast();
23489            try {
23490                for (int i = 0; i < count; i++) {
23491                    IOnPermissionsChangeListener callback = mPermissionListeners
23492                            .getBroadcastItem(i);
23493                    try {
23494                        callback.onPermissionsChanged(uid);
23495                    } catch (RemoteException e) {
23496                        Log.e(TAG, "Permission listener is dead", e);
23497                    }
23498                }
23499            } finally {
23500                mPermissionListeners.finishBroadcast();
23501            }
23502        }
23503    }
23504
23505    private class PackageManagerNative extends IPackageManagerNative.Stub {
23506        @Override
23507        public String[] getNamesForUids(int[] uids) throws RemoteException {
23508            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23509            // massage results so they can be parsed by the native binder
23510            for (int i = results.length - 1; i >= 0; --i) {
23511                if (results[i] == null) {
23512                    results[i] = "";
23513                }
23514            }
23515            return results;
23516        }
23517
23518        // NB: this differentiates between preloads and sideloads
23519        @Override
23520        public String getInstallerForPackage(String packageName) throws RemoteException {
23521            final String installerName = getInstallerPackageName(packageName);
23522            if (!TextUtils.isEmpty(installerName)) {
23523                return installerName;
23524            }
23525            // differentiate between preload and sideload
23526            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23527            ApplicationInfo appInfo = getApplicationInfo(packageName,
23528                                    /*flags*/ 0,
23529                                    /*userId*/ callingUser);
23530            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23531                return "preload";
23532            }
23533            return "";
23534        }
23535
23536        @Override
23537        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23538            try {
23539                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23540                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23541                if (pInfo != null) {
23542                    return pInfo.getLongVersionCode();
23543                }
23544            } catch (Exception e) {
23545            }
23546            return 0;
23547        }
23548    }
23549
23550    private class PackageManagerInternalImpl extends PackageManagerInternal {
23551        @Override
23552        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23553                int flagValues, int userId) {
23554            PackageManagerService.this.updatePermissionFlags(
23555                    permName, packageName, flagMask, flagValues, userId);
23556        }
23557
23558        @Override
23559        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23560            SigningDetails sd = getSigningDetails(packageName);
23561            if (sd == null) {
23562                return false;
23563            }
23564            return sd.hasSha256Certificate(restoringFromSigHash,
23565                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23566        }
23567
23568        @Override
23569        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23570            SigningDetails sd = getSigningDetails(packageName);
23571            if (sd == null) {
23572                return false;
23573            }
23574            return sd.hasCertificate(restoringFromSig,
23575                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23576        }
23577
23578        @Override
23579        public boolean hasSignatureCapability(int serverUid, int clientUid,
23580                @SigningDetails.CertCapabilities int capability) {
23581            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23582            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23583            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23584                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23585
23586        }
23587
23588        private SigningDetails getSigningDetails(@NonNull String packageName) {
23589            synchronized (mPackages) {
23590                PackageParser.Package p = mPackages.get(packageName);
23591                if (p == null) {
23592                    return null;
23593                }
23594                return p.mSigningDetails;
23595            }
23596        }
23597
23598        private SigningDetails getSigningDetails(int uid) {
23599            synchronized (mPackages) {
23600                final Object obj = mSettings.getUserIdLPr(uid);
23601                if (obj != null) {
23602                    if (obj instanceof SharedUserSetting) {
23603                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23604                    } else if (obj instanceof PackageSetting) {
23605                        final PackageSetting ps = (PackageSetting) obj;
23606                        return ps.signatures.mSigningDetails;
23607                    }
23608                }
23609                return SigningDetails.UNKNOWN;
23610            }
23611        }
23612
23613        @Override
23614        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23615            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23616        }
23617
23618        @Override
23619        public boolean isInstantApp(String packageName, int userId) {
23620            return PackageManagerService.this.isInstantApp(packageName, userId);
23621        }
23622
23623        @Override
23624        public String getInstantAppPackageName(int uid) {
23625            return PackageManagerService.this.getInstantAppPackageName(uid);
23626        }
23627
23628        @Override
23629        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23630            synchronized (mPackages) {
23631                return PackageManagerService.this.filterAppAccessLPr(
23632                        (PackageSetting) pkg.mExtras, callingUid, userId);
23633            }
23634        }
23635
23636        @Override
23637        public PackageParser.Package getPackage(String packageName) {
23638            synchronized (mPackages) {
23639                packageName = resolveInternalPackageNameLPr(
23640                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23641                return mPackages.get(packageName);
23642            }
23643        }
23644
23645        @Override
23646        public PackageList getPackageList(PackageListObserver observer) {
23647            synchronized (mPackages) {
23648                final int N = mPackages.size();
23649                final ArrayList<String> list = new ArrayList<>(N);
23650                for (int i = 0; i < N; i++) {
23651                    list.add(mPackages.keyAt(i));
23652                }
23653                final PackageList packageList = new PackageList(list, observer);
23654                if (observer != null) {
23655                    mPackageListObservers.add(packageList);
23656                }
23657                return packageList;
23658            }
23659        }
23660
23661        @Override
23662        public void removePackageListObserver(PackageListObserver observer) {
23663            synchronized (mPackages) {
23664                mPackageListObservers.remove(observer);
23665            }
23666        }
23667
23668        @Override
23669        public PackageParser.Package getDisabledPackage(String packageName) {
23670            synchronized (mPackages) {
23671                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23672                return (ps != null) ? ps.pkg : null;
23673            }
23674        }
23675
23676        @Override
23677        public String getKnownPackageName(int knownPackage, int userId) {
23678            switch(knownPackage) {
23679                case PackageManagerInternal.PACKAGE_BROWSER:
23680                    return getDefaultBrowserPackageName(userId);
23681                case PackageManagerInternal.PACKAGE_INSTALLER:
23682                    return mRequiredInstallerPackage;
23683                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23684                    return mSetupWizardPackage;
23685                case PackageManagerInternal.PACKAGE_SYSTEM:
23686                    return "android";
23687                case PackageManagerInternal.PACKAGE_VERIFIER:
23688                    return mRequiredVerifierPackage;
23689                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23690                    return mSystemTextClassifierPackage;
23691            }
23692            return null;
23693        }
23694
23695        @Override
23696        public boolean isResolveActivityComponent(ComponentInfo component) {
23697            return mResolveActivity.packageName.equals(component.packageName)
23698                    && mResolveActivity.name.equals(component.name);
23699        }
23700
23701        @Override
23702        public void setLocationPackagesProvider(PackagesProvider provider) {
23703            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23704        }
23705
23706        @Override
23707        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23708            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23709        }
23710
23711        @Override
23712        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23713            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23714        }
23715
23716        @Override
23717        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23718            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23719        }
23720
23721        @Override
23722        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23723            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23724        }
23725
23726        @Override
23727        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23728            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23729        }
23730
23731        @Override
23732        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23733            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23734        }
23735
23736        @Override
23737        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23738            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23739        }
23740
23741        @Override
23742        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23743            synchronized (mPackages) {
23744                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23745            }
23746            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23747        }
23748
23749        @Override
23750        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23751            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23752                    packageName, userId);
23753        }
23754
23755        @Override
23756        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23757            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23758                    packageName, userId);
23759        }
23760
23761        @Override
23762        public void setKeepUninstalledPackages(final List<String> packageList) {
23763            Preconditions.checkNotNull(packageList);
23764            List<String> removedFromList = null;
23765            synchronized (mPackages) {
23766                if (mKeepUninstalledPackages != null) {
23767                    final int packagesCount = mKeepUninstalledPackages.size();
23768                    for (int i = 0; i < packagesCount; i++) {
23769                        String oldPackage = mKeepUninstalledPackages.get(i);
23770                        if (packageList != null && packageList.contains(oldPackage)) {
23771                            continue;
23772                        }
23773                        if (removedFromList == null) {
23774                            removedFromList = new ArrayList<>();
23775                        }
23776                        removedFromList.add(oldPackage);
23777                    }
23778                }
23779                mKeepUninstalledPackages = new ArrayList<>(packageList);
23780                if (removedFromList != null) {
23781                    final int removedCount = removedFromList.size();
23782                    for (int i = 0; i < removedCount; i++) {
23783                        deletePackageIfUnusedLPr(removedFromList.get(i));
23784                    }
23785                }
23786            }
23787        }
23788
23789        @Override
23790        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23791            synchronized (mPackages) {
23792                return mPermissionManager.isPermissionsReviewRequired(
23793                        mPackages.get(packageName), userId);
23794            }
23795        }
23796
23797        @Override
23798        public PackageInfo getPackageInfo(
23799                String packageName, int flags, int filterCallingUid, int userId) {
23800            return PackageManagerService.this
23801                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23802                            flags, filterCallingUid, userId);
23803        }
23804
23805        @Override
23806        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23807            synchronized (mPackages) {
23808                final PackageSetting ps = mSettings.mPackages.get(packageName);
23809                PersistableBundle launcherExtras = null;
23810                if (ps != null) {
23811                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23812                }
23813                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23814            }
23815        }
23816
23817        @Override
23818        public boolean isPackageSuspended(String packageName, int userId) {
23819            synchronized (mPackages) {
23820                final PackageSetting ps = mSettings.mPackages.get(packageName);
23821                return (ps != null) ? ps.getSuspended(userId) : false;
23822            }
23823        }
23824
23825        @Override
23826        public String getSuspendingPackage(String suspendedPackage, int userId) {
23827            synchronized (mPackages) {
23828                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23829                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23830            }
23831        }
23832
23833        @Override
23834        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23835            synchronized (mPackages) {
23836                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23837                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23838            }
23839        }
23840
23841        @Override
23842        public int getPackageUid(String packageName, int flags, int userId) {
23843            return PackageManagerService.this
23844                    .getPackageUid(packageName, flags, userId);
23845        }
23846
23847        @Override
23848        public ApplicationInfo getApplicationInfo(
23849                String packageName, int flags, int filterCallingUid, int userId) {
23850            return PackageManagerService.this
23851                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23852        }
23853
23854        @Override
23855        public ActivityInfo getActivityInfo(
23856                ComponentName component, int flags, int filterCallingUid, int userId) {
23857            return PackageManagerService.this
23858                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23859        }
23860
23861        @Override
23862        public List<ResolveInfo> queryIntentActivities(
23863                Intent intent, int flags, int filterCallingUid, int userId) {
23864            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23865            return PackageManagerService.this
23866                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23867                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23868        }
23869
23870        @Override
23871        public List<ResolveInfo> queryIntentServices(
23872                Intent intent, int flags, int callingUid, int userId) {
23873            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23874            return PackageManagerService.this
23875                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23876                            false);
23877        }
23878
23879        @Override
23880        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23881                int userId) {
23882            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23883        }
23884
23885        @Override
23886        public ComponentName getDefaultHomeActivity(int userId) {
23887            return PackageManagerService.this.getDefaultHomeActivity(userId);
23888        }
23889
23890        @Override
23891        public void setDeviceAndProfileOwnerPackages(
23892                int deviceOwnerUserId, String deviceOwnerPackage,
23893                SparseArray<String> profileOwnerPackages) {
23894            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23895                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23896        }
23897
23898        @Override
23899        public boolean isPackageDataProtected(int userId, String packageName) {
23900            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23901        }
23902
23903        @Override
23904        public boolean isPackageStateProtected(String packageName, int userId) {
23905            return mProtectedPackages.isPackageStateProtected(userId, packageName);
23906        }
23907
23908        @Override
23909        public boolean isPackageEphemeral(int userId, String packageName) {
23910            synchronized (mPackages) {
23911                final PackageSetting ps = mSettings.mPackages.get(packageName);
23912                return ps != null ? ps.getInstantApp(userId) : false;
23913            }
23914        }
23915
23916        @Override
23917        public boolean wasPackageEverLaunched(String packageName, int userId) {
23918            synchronized (mPackages) {
23919                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23920            }
23921        }
23922
23923        @Override
23924        public void grantRuntimePermission(String packageName, String permName, int userId,
23925                boolean overridePolicy) {
23926            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23927                    permName, packageName, overridePolicy, getCallingUid(), userId,
23928                    mPermissionCallback);
23929        }
23930
23931        @Override
23932        public void revokeRuntimePermission(String packageName, String permName, int userId,
23933                boolean overridePolicy) {
23934            mPermissionManager.revokeRuntimePermission(
23935                    permName, packageName, overridePolicy, getCallingUid(), userId,
23936                    mPermissionCallback);
23937        }
23938
23939        @Override
23940        public String getNameForUid(int uid) {
23941            return PackageManagerService.this.getNameForUid(uid);
23942        }
23943
23944        @Override
23945        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23946                Intent origIntent, String resolvedType, String callingPackage,
23947                Bundle verificationBundle, int userId) {
23948            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23949                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23950                    userId);
23951        }
23952
23953        @Override
23954        public void grantEphemeralAccess(int userId, Intent intent,
23955                int targetAppId, int ephemeralAppId) {
23956            synchronized (mPackages) {
23957                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23958                        targetAppId, ephemeralAppId);
23959            }
23960        }
23961
23962        @Override
23963        public boolean isInstantAppInstallerComponent(ComponentName component) {
23964            synchronized (mPackages) {
23965                return mInstantAppInstallerActivity != null
23966                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23967            }
23968        }
23969
23970        @Override
23971        public void pruneInstantApps() {
23972            mInstantAppRegistry.pruneInstantApps();
23973        }
23974
23975        @Override
23976        public String getSetupWizardPackageName() {
23977            return mSetupWizardPackage;
23978        }
23979
23980        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23981            if (policy != null) {
23982                mExternalSourcesPolicy = policy;
23983            }
23984        }
23985
23986        @Override
23987        public boolean isPackagePersistent(String packageName) {
23988            synchronized (mPackages) {
23989                PackageParser.Package pkg = mPackages.get(packageName);
23990                return pkg != null
23991                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23992                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23993                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23994                        : false;
23995            }
23996        }
23997
23998        @Override
23999        public boolean isLegacySystemApp(Package pkg) {
24000            synchronized (mPackages) {
24001                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24002                return mPromoteSystemApps
24003                        && ps.isSystem()
24004                        && mExistingSystemPackages.contains(ps.name);
24005            }
24006        }
24007
24008        @Override
24009        public List<PackageInfo> getOverlayPackages(int userId) {
24010            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24011            synchronized (mPackages) {
24012                for (PackageParser.Package p : mPackages.values()) {
24013                    if (p.mOverlayTarget != null) {
24014                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24015                        if (pkg != null) {
24016                            overlayPackages.add(pkg);
24017                        }
24018                    }
24019                }
24020            }
24021            return overlayPackages;
24022        }
24023
24024        @Override
24025        public List<String> getTargetPackageNames(int userId) {
24026            List<String> targetPackages = new ArrayList<>();
24027            synchronized (mPackages) {
24028                for (PackageParser.Package p : mPackages.values()) {
24029                    if (p.mOverlayTarget == null) {
24030                        targetPackages.add(p.packageName);
24031                    }
24032                }
24033            }
24034            return targetPackages;
24035        }
24036
24037        @Override
24038        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24039                @Nullable List<String> overlayPackageNames) {
24040            synchronized (mPackages) {
24041                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24042                    Slog.e(TAG, "failed to find package " + targetPackageName);
24043                    return false;
24044                }
24045                ArrayList<String> overlayPaths = null;
24046                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24047                    final int N = overlayPackageNames.size();
24048                    overlayPaths = new ArrayList<>(N);
24049                    for (int i = 0; i < N; i++) {
24050                        final String packageName = overlayPackageNames.get(i);
24051                        final PackageParser.Package pkg = mPackages.get(packageName);
24052                        if (pkg == null) {
24053                            Slog.e(TAG, "failed to find package " + packageName);
24054                            return false;
24055                        }
24056                        overlayPaths.add(pkg.baseCodePath);
24057                    }
24058                }
24059
24060                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24061                ps.setOverlayPaths(overlayPaths, userId);
24062                return true;
24063            }
24064        }
24065
24066        @Override
24067        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24068                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24069            return resolveIntentInternal(
24070                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24071        }
24072
24073        @Override
24074        public ResolveInfo resolveService(Intent intent, String resolvedType,
24075                int flags, int userId, int callingUid) {
24076            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24077        }
24078
24079        @Override
24080        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24081            return PackageManagerService.this.resolveContentProviderInternal(
24082                    name, flags, userId);
24083        }
24084
24085        @Override
24086        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24087            synchronized (mPackages) {
24088                mIsolatedOwners.put(isolatedUid, ownerUid);
24089            }
24090        }
24091
24092        @Override
24093        public void removeIsolatedUid(int isolatedUid) {
24094            synchronized (mPackages) {
24095                mIsolatedOwners.delete(isolatedUid);
24096            }
24097        }
24098
24099        @Override
24100        public int getUidTargetSdkVersion(int uid) {
24101            synchronized (mPackages) {
24102                return getUidTargetSdkVersionLockedLPr(uid);
24103            }
24104        }
24105
24106        @Override
24107        public int getPackageTargetSdkVersion(String packageName) {
24108            synchronized (mPackages) {
24109                return getPackageTargetSdkVersionLockedLPr(packageName);
24110            }
24111        }
24112
24113        @Override
24114        public boolean canAccessInstantApps(int callingUid, int userId) {
24115            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24116        }
24117
24118        @Override
24119        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24120            synchronized (mPackages) {
24121                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24122                return !PackageManagerService.this.filterAppAccessLPr(
24123                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24124            }
24125        }
24126
24127        @Override
24128        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24129            synchronized (mPackages) {
24130                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24131            }
24132        }
24133
24134        @Override
24135        public void notifyPackageUse(String packageName, int reason) {
24136            synchronized (mPackages) {
24137                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24138            }
24139        }
24140    }
24141
24142    @Override
24143    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24144        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24145        synchronized (mPackages) {
24146            final long identity = Binder.clearCallingIdentity();
24147            try {
24148                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24149                        packageNames, userId);
24150            } finally {
24151                Binder.restoreCallingIdentity(identity);
24152            }
24153        }
24154    }
24155
24156    @Override
24157    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24158        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24159        synchronized (mPackages) {
24160            final long identity = Binder.clearCallingIdentity();
24161            try {
24162                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24163                        packageNames, userId);
24164            } finally {
24165                Binder.restoreCallingIdentity(identity);
24166            }
24167        }
24168    }
24169
24170    @Override
24171    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24172            String[] packageNames, int userId) {
24173        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24174        synchronized (mPackages) {
24175            Binder.withCleanCallingIdentity( () -> {
24176                mDefaultPermissionPolicy.
24177                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24178                                packageNames, userId);
24179            });
24180        }
24181    }
24182
24183    @Override
24184    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24185            String[] packageNames, int userId) {
24186        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24187        synchronized (mPackages) {
24188            Binder.withCleanCallingIdentity( () -> {
24189                mDefaultPermissionPolicy.
24190                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24191                                packageNames, userId);
24192            });
24193        }
24194    }
24195
24196    @Override
24197    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24198        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24199        synchronized (mPackages) {
24200            final long identity = Binder.clearCallingIdentity();
24201            try {
24202                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24203                        packageName, userId);
24204            } finally {
24205                Binder.restoreCallingIdentity(identity);
24206            }
24207        }
24208    }
24209
24210    @Override
24211    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24212        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24213        synchronized (mPackages) {
24214            final long identity = Binder.clearCallingIdentity();
24215            try {
24216                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24217            } finally {
24218                Binder.restoreCallingIdentity(identity);
24219            }
24220        }
24221    }
24222
24223    private static void enforceSystemOrPhoneCaller(String tag) {
24224        int callingUid = Binder.getCallingUid();
24225        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24226            throw new SecurityException(
24227                    "Cannot call " + tag + " from UID " + callingUid);
24228        }
24229    }
24230
24231    boolean isHistoricalPackageUsageAvailable() {
24232        return mPackageUsage.isHistoricalPackageUsageAvailable();
24233    }
24234
24235    /**
24236     * Return a <b>copy</b> of the collection of packages known to the package manager.
24237     * @return A copy of the values of mPackages.
24238     */
24239    Collection<PackageParser.Package> getPackages() {
24240        synchronized (mPackages) {
24241            return new ArrayList<>(mPackages.values());
24242        }
24243    }
24244
24245    /**
24246     * Logs process start information (including base APK hash) to the security log.
24247     * @hide
24248     */
24249    @Override
24250    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24251            String apkFile, int pid) {
24252        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24253            return;
24254        }
24255        if (!SecurityLog.isLoggingEnabled()) {
24256            return;
24257        }
24258        Bundle data = new Bundle();
24259        data.putLong("startTimestamp", System.currentTimeMillis());
24260        data.putString("processName", processName);
24261        data.putInt("uid", uid);
24262        data.putString("seinfo", seinfo);
24263        data.putString("apkFile", apkFile);
24264        data.putInt("pid", pid);
24265        Message msg = mProcessLoggingHandler.obtainMessage(
24266                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24267        msg.setData(data);
24268        mProcessLoggingHandler.sendMessage(msg);
24269    }
24270
24271    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24272        return mCompilerStats.getPackageStats(pkgName);
24273    }
24274
24275    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24276        return getOrCreateCompilerPackageStats(pkg.packageName);
24277    }
24278
24279    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24280        return mCompilerStats.getOrCreatePackageStats(pkgName);
24281    }
24282
24283    public void deleteCompilerPackageStats(String pkgName) {
24284        mCompilerStats.deletePackageStats(pkgName);
24285    }
24286
24287    @Override
24288    public int getInstallReason(String packageName, int userId) {
24289        final int callingUid = Binder.getCallingUid();
24290        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24291                true /* requireFullPermission */, false /* checkShell */,
24292                "get install reason");
24293        synchronized (mPackages) {
24294            final PackageSetting ps = mSettings.mPackages.get(packageName);
24295            if (filterAppAccessLPr(ps, callingUid, userId)) {
24296                return PackageManager.INSTALL_REASON_UNKNOWN;
24297            }
24298            if (ps != null) {
24299                return ps.getInstallReason(userId);
24300            }
24301        }
24302        return PackageManager.INSTALL_REASON_UNKNOWN;
24303    }
24304
24305    @Override
24306    public boolean canRequestPackageInstalls(String packageName, int userId) {
24307        return canRequestPackageInstallsInternal(packageName, 0, userId,
24308                true /* throwIfPermNotDeclared*/);
24309    }
24310
24311    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24312            boolean throwIfPermNotDeclared) {
24313        int callingUid = Binder.getCallingUid();
24314        int uid = getPackageUid(packageName, 0, userId);
24315        if (callingUid != uid && callingUid != Process.ROOT_UID
24316                && callingUid != Process.SYSTEM_UID) {
24317            throw new SecurityException(
24318                    "Caller uid " + callingUid + " does not own package " + packageName);
24319        }
24320        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24321        if (info == null) {
24322            return false;
24323        }
24324        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24325            return false;
24326        }
24327        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24328        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24329        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24330            if (throwIfPermNotDeclared) {
24331                throw new SecurityException("Need to declare " + appOpPermission
24332                        + " to call this api");
24333            } else {
24334                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24335                return false;
24336            }
24337        }
24338        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24339            return false;
24340        }
24341        if (mExternalSourcesPolicy != null) {
24342            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24343            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24344                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24345            }
24346        }
24347        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24348    }
24349
24350    @Override
24351    public ComponentName getInstantAppResolverSettingsComponent() {
24352        return mInstantAppResolverSettingsComponent;
24353    }
24354
24355    @Override
24356    public ComponentName getInstantAppInstallerComponent() {
24357        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24358            return null;
24359        }
24360        return mInstantAppInstallerActivity == null
24361                ? null : mInstantAppInstallerActivity.getComponentName();
24362    }
24363
24364    @Override
24365    public String getInstantAppAndroidId(String packageName, int userId) {
24366        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24367                "getInstantAppAndroidId");
24368        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24369                true /* requireFullPermission */, false /* checkShell */,
24370                "getInstantAppAndroidId");
24371        // Make sure the target is an Instant App.
24372        if (!isInstantApp(packageName, userId)) {
24373            return null;
24374        }
24375        synchronized (mPackages) {
24376            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24377        }
24378    }
24379
24380    boolean canHaveOatDir(String packageName) {
24381        synchronized (mPackages) {
24382            PackageParser.Package p = mPackages.get(packageName);
24383            if (p == null) {
24384                return false;
24385            }
24386            return p.canHaveOatDir();
24387        }
24388    }
24389
24390    private String getOatDir(PackageParser.Package pkg) {
24391        if (!pkg.canHaveOatDir()) {
24392            return null;
24393        }
24394        File codePath = new File(pkg.codePath);
24395        if (codePath.isDirectory()) {
24396            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24397        }
24398        return null;
24399    }
24400
24401    void deleteOatArtifactsOfPackage(String packageName) {
24402        final String[] instructionSets;
24403        final List<String> codePaths;
24404        final String oatDir;
24405        final PackageParser.Package pkg;
24406        synchronized (mPackages) {
24407            pkg = mPackages.get(packageName);
24408        }
24409        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24410        codePaths = pkg.getAllCodePaths();
24411        oatDir = getOatDir(pkg);
24412
24413        for (String codePath : codePaths) {
24414            for (String isa : instructionSets) {
24415                try {
24416                    mInstaller.deleteOdex(codePath, isa, oatDir);
24417                } catch (InstallerException e) {
24418                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24419                }
24420            }
24421        }
24422    }
24423
24424    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24425        Set<String> unusedPackages = new HashSet<>();
24426        long currentTimeInMillis = System.currentTimeMillis();
24427        synchronized (mPackages) {
24428            for (PackageParser.Package pkg : mPackages.values()) {
24429                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24430                if (ps == null) {
24431                    continue;
24432                }
24433                PackageDexUsage.PackageUseInfo packageUseInfo =
24434                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24435                if (PackageManagerServiceUtils
24436                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24437                                downgradeTimeThresholdMillis, packageUseInfo,
24438                                pkg.getLatestPackageUseTimeInMills(),
24439                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24440                    unusedPackages.add(pkg.packageName);
24441                }
24442            }
24443        }
24444        return unusedPackages;
24445    }
24446
24447    @Override
24448    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24449            int userId) {
24450        final int callingUid = Binder.getCallingUid();
24451        final int callingAppId = UserHandle.getAppId(callingUid);
24452
24453        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24454                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24455
24456        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24457                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24458            throw new SecurityException("Caller must have the "
24459                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24460        }
24461
24462        synchronized(mPackages) {
24463            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24464            scheduleWritePackageRestrictionsLocked(userId);
24465        }
24466    }
24467
24468    @Nullable
24469    @Override
24470    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24471        final int callingUid = Binder.getCallingUid();
24472        final int callingAppId = UserHandle.getAppId(callingUid);
24473
24474        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24475                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24476
24477        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24478                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24479            throw new SecurityException("Caller must have the "
24480                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24481        }
24482
24483        synchronized(mPackages) {
24484            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24485        }
24486    }
24487
24488    @Override
24489    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24490        final int callingUid = Binder.getCallingUid();
24491        final int callingAppId = UserHandle.getAppId(callingUid);
24492
24493        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24494                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24495
24496        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24497                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24498            throw new SecurityException("Caller must have the "
24499                    + MANAGE_DEVICE_ADMINS + " permission.");
24500        }
24501
24502        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24503    }
24504}
24505
24506interface PackageSender {
24507    /**
24508     * @param userIds User IDs where the action occurred on a full application
24509     * @param instantUserIds User IDs where the action occurred on an instant application
24510     */
24511    void sendPackageBroadcast(final String action, final String pkg,
24512        final Bundle extras, final int flags, final String targetPkg,
24513        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24514    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24515        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24516    void notifyPackageAdded(String packageName);
24517    void notifyPackageRemoved(String packageName);
24518}
24519