PackageManagerService.java revision 151b21b227eb9da41548f137a3a94d5c7d44eb69
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
94import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
95import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.SELinuxUtil;
190import android.content.pm.ServiceInfo;
191import android.content.pm.SharedLibraryInfo;
192import android.content.pm.Signature;
193import android.content.pm.UserInfo;
194import android.content.pm.VerifierDeviceIdentity;
195import android.content.pm.VerifierInfo;
196import android.content.pm.VersionedPackage;
197import android.content.pm.dex.ArtManager;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.AsyncTask;
206import android.os.Binder;
207import android.os.Build;
208import android.os.Bundle;
209import android.os.Debug;
210import android.os.Environment;
211import android.os.Environment.UserEnvironment;
212import android.os.FileUtils;
213import android.os.Handler;
214import android.os.IBinder;
215import android.os.Looper;
216import android.os.Message;
217import android.os.Parcel;
218import android.os.ParcelFileDescriptor;
219import android.os.PatternMatcher;
220import android.os.PersistableBundle;
221import android.os.Process;
222import android.os.RemoteCallbackList;
223import android.os.RemoteException;
224import android.os.ResultReceiver;
225import android.os.SELinux;
226import android.os.ServiceManager;
227import android.os.ShellCallback;
228import android.os.SystemClock;
229import android.os.SystemProperties;
230import android.os.Trace;
231import android.os.UserHandle;
232import android.os.UserManager;
233import android.os.UserManagerInternal;
234import android.os.storage.IStorageManager;
235import android.os.storage.StorageEventListener;
236import android.os.storage.StorageManager;
237import android.os.storage.StorageManagerInternal;
238import android.os.storage.VolumeInfo;
239import android.os.storage.VolumeRecord;
240import android.provider.Settings.Global;
241import android.provider.Settings.Secure;
242import android.security.KeyStore;
243import android.security.SystemKeyStore;
244import android.service.pm.PackageServiceDumpProto;
245import android.system.ErrnoException;
246import android.system.Os;
247import android.text.TextUtils;
248import android.text.format.DateUtils;
249import android.util.ArrayMap;
250import android.util.ArraySet;
251import android.util.Base64;
252import android.util.ByteStringUtils;
253import android.util.DisplayMetrics;
254import android.util.EventLog;
255import android.util.ExceptionUtils;
256import android.util.Log;
257import android.util.LogPrinter;
258import android.util.LongSparseArray;
259import android.util.LongSparseLongArray;
260import android.util.MathUtils;
261import android.util.PackageUtils;
262import android.util.Pair;
263import android.util.PrintStreamPrinter;
264import android.util.Slog;
265import android.util.SparseArray;
266import android.util.SparseBooleanArray;
267import android.util.SparseIntArray;
268import android.util.TimingsTraceLog;
269import android.util.Xml;
270import android.util.jar.StrictJarFile;
271import android.util.proto.ProtoOutputStream;
272import android.view.Display;
273
274import com.android.internal.R;
275import com.android.internal.annotations.GuardedBy;
276import com.android.internal.app.IMediaContainerService;
277import com.android.internal.app.ResolverActivity;
278import com.android.internal.content.NativeLibraryHelper;
279import com.android.internal.content.PackageHelper;
280import com.android.internal.logging.MetricsLogger;
281import com.android.internal.os.IParcelFileDescriptorFactory;
282import com.android.internal.os.SomeArgs;
283import com.android.internal.os.Zygote;
284import com.android.internal.telephony.CarrierAppUtils;
285import com.android.internal.util.ArrayUtils;
286import com.android.internal.util.ConcurrentUtils;
287import com.android.internal.util.DumpUtils;
288import com.android.internal.util.FastXmlSerializer;
289import com.android.internal.util.IndentingPrintWriter;
290import com.android.internal.util.Preconditions;
291import com.android.internal.util.XmlUtils;
292import com.android.server.AttributeCache;
293import com.android.server.DeviceIdleController;
294import com.android.server.EventLogTags;
295import com.android.server.FgThread;
296import com.android.server.IntentResolver;
297import com.android.server.LocalServices;
298import com.android.server.LockGuard;
299import com.android.server.ServiceThread;
300import com.android.server.SystemConfig;
301import com.android.server.SystemServerInitThreadPool;
302import com.android.server.Watchdog;
303import com.android.server.net.NetworkPolicyManagerInternal;
304import com.android.server.pm.Installer.InstallerException;
305import com.android.server.pm.Settings.DatabaseVersion;
306import com.android.server.pm.Settings.VersionInfo;
307import com.android.server.pm.dex.ArtManagerService;
308import com.android.server.pm.dex.DexLogger;
309import com.android.server.pm.dex.DexManager;
310import com.android.server.pm.dex.DexoptOptions;
311import com.android.server.pm.dex.PackageDexUsage;
312import com.android.server.pm.permission.BasePermission;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
314import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
315import com.android.server.pm.permission.PermissionManagerInternal;
316import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
317import com.android.server.pm.permission.PermissionManagerService;
318import com.android.server.pm.permission.PermissionsState;
319import com.android.server.pm.permission.PermissionsState.PermissionState;
320import com.android.server.security.VerityUtils;
321import com.android.server.storage.DeviceStorageMonitorInternal;
322
323import dalvik.system.CloseGuard;
324import dalvik.system.VMRuntime;
325
326import libcore.io.IoUtils;
327
328import org.xmlpull.v1.XmlPullParser;
329import org.xmlpull.v1.XmlPullParserException;
330import org.xmlpull.v1.XmlSerializer;
331
332import java.io.BufferedOutputStream;
333import java.io.ByteArrayInputStream;
334import java.io.ByteArrayOutputStream;
335import java.io.File;
336import java.io.FileDescriptor;
337import java.io.FileInputStream;
338import java.io.FileOutputStream;
339import java.io.FilenameFilter;
340import java.io.IOException;
341import java.io.PrintWriter;
342import java.lang.annotation.Retention;
343import java.lang.annotation.RetentionPolicy;
344import java.nio.charset.StandardCharsets;
345import java.security.DigestException;
346import java.security.DigestInputStream;
347import java.security.MessageDigest;
348import java.security.NoSuchAlgorithmException;
349import java.security.PublicKey;
350import java.security.SecureRandom;
351import java.security.cert.CertificateException;
352import java.util.ArrayList;
353import java.util.Arrays;
354import java.util.Collection;
355import java.util.Collections;
356import java.util.Comparator;
357import java.util.HashMap;
358import java.util.HashSet;
359import java.util.Iterator;
360import java.util.LinkedHashSet;
361import java.util.List;
362import java.util.Map;
363import java.util.Objects;
364import java.util.Set;
365import java.util.concurrent.CountDownLatch;
366import java.util.concurrent.Future;
367import java.util.concurrent.TimeUnit;
368import java.util.concurrent.atomic.AtomicBoolean;
369import java.util.concurrent.atomic.AtomicInteger;
370
371/**
372 * Keep track of all those APKs everywhere.
373 * <p>
374 * Internally there are two important locks:
375 * <ul>
376 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
377 * and other related state. It is a fine-grained lock that should only be held
378 * momentarily, as it's one of the most contended locks in the system.
379 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
380 * operations typically involve heavy lifting of application data on disk. Since
381 * {@code installd} is single-threaded, and it's operations can often be slow,
382 * this lock should never be acquired while already holding {@link #mPackages}.
383 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
384 * holding {@link #mInstallLock}.
385 * </ul>
386 * Many internal methods rely on the caller to hold the appropriate locks, and
387 * this contract is expressed through method name suffixes:
388 * <ul>
389 * <li>fooLI(): the caller must hold {@link #mInstallLock}
390 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
391 * being modified must be frozen
392 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
393 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
394 * </ul>
395 * <p>
396 * Because this class is very central to the platform's security; please run all
397 * CTS and unit tests whenever making modifications:
398 *
399 * <pre>
400 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
401 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
402 * </pre>
403 */
404public class PackageManagerService extends IPackageManager.Stub
405        implements PackageSender {
406    static final String TAG = "PackageManager";
407    public static final boolean DEBUG_SETTINGS = false;
408    static final boolean DEBUG_PREFERRED = false;
409    static final boolean DEBUG_UPGRADE = false;
410    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
411    private static final boolean DEBUG_BACKUP = false;
412    public static final boolean DEBUG_INSTALL = false;
413    public static final boolean DEBUG_REMOVE = false;
414    private static final boolean DEBUG_BROADCASTS = false;
415    private static final boolean DEBUG_SHOW_INFO = false;
416    private static final boolean DEBUG_PACKAGE_INFO = false;
417    private static final boolean DEBUG_INTENT_MATCHING = false;
418    public static final boolean DEBUG_PACKAGE_SCANNING = false;
419    private static final boolean DEBUG_VERIFY = false;
420    private static final boolean DEBUG_FILTERS = false;
421    public static final boolean DEBUG_PERMISSIONS = false;
422    private static final boolean DEBUG_SHARED_LIBRARIES = false;
423    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
424
425    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
426    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
427    // user, but by default initialize to this.
428    public static final boolean DEBUG_DEXOPT = false;
429
430    private static final boolean DEBUG_ABI_SELECTION = false;
431    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
432    private static final boolean DEBUG_TRIAGED_MISSING = false;
433    private static final boolean DEBUG_APP_DATA = false;
434
435    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
436    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
437
438    private static final boolean HIDE_EPHEMERAL_APIS = false;
439
440    private static final boolean ENABLE_FREE_CACHE_V2 =
441            SystemProperties.getBoolean("fw.free_cache_v2", true);
442
443    private static final int RADIO_UID = Process.PHONE_UID;
444    private static final int LOG_UID = Process.LOG_UID;
445    private static final int NFC_UID = Process.NFC_UID;
446    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
447    private static final int SHELL_UID = Process.SHELL_UID;
448    private static final int SE_UID = Process.SE_UID;
449
450    // Suffix used during package installation when copying/moving
451    // package apks to install directory.
452    private static final String INSTALL_PACKAGE_SUFFIX = "-";
453
454    static final int SCAN_NO_DEX = 1<<0;
455    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
456    static final int SCAN_NEW_INSTALL = 1<<2;
457    static final int SCAN_UPDATE_TIME = 1<<3;
458    static final int SCAN_BOOTING = 1<<4;
459    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
460    static final int SCAN_REQUIRE_KNOWN = 1<<7;
461    static final int SCAN_MOVE = 1<<8;
462    static final int SCAN_INITIAL = 1<<9;
463    static final int SCAN_CHECK_ONLY = 1<<10;
464    static final int SCAN_DONT_KILL_APP = 1<<11;
465    static final int SCAN_IGNORE_FROZEN = 1<<12;
466    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
467    static final int SCAN_AS_INSTANT_APP = 1<<14;
468    static final int SCAN_AS_FULL_APP = 1<<15;
469    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
470    static final int SCAN_AS_SYSTEM = 1<<17;
471    static final int SCAN_AS_PRIVILEGED = 1<<18;
472    static final int SCAN_AS_OEM = 1<<19;
473    static final int SCAN_AS_VENDOR = 1<<20;
474    static final int SCAN_AS_PRODUCT = 1<<21;
475
476    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
477            SCAN_NO_DEX,
478            SCAN_UPDATE_SIGNATURE,
479            SCAN_NEW_INSTALL,
480            SCAN_UPDATE_TIME,
481            SCAN_BOOTING,
482            SCAN_DELETE_DATA_ON_FAILURES,
483            SCAN_REQUIRE_KNOWN,
484            SCAN_MOVE,
485            SCAN_INITIAL,
486            SCAN_CHECK_ONLY,
487            SCAN_DONT_KILL_APP,
488            SCAN_IGNORE_FROZEN,
489            SCAN_FIRST_BOOT_OR_UPGRADE,
490            SCAN_AS_INSTANT_APP,
491            SCAN_AS_FULL_APP,
492            SCAN_AS_VIRTUAL_PRELOAD,
493    })
494    @Retention(RetentionPolicy.SOURCE)
495    public @interface ScanFlags {}
496
497    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
498    /** Extension of the compressed packages */
499    public final static String COMPRESSED_EXTENSION = ".gz";
500    /** Suffix of stub packages on the system partition */
501    public final static String STUB_SUFFIX = "-Stub";
502
503    private static final int[] EMPTY_INT_ARRAY = new int[0];
504
505    private static final int TYPE_UNKNOWN = 0;
506    private static final int TYPE_ACTIVITY = 1;
507    private static final int TYPE_RECEIVER = 2;
508    private static final int TYPE_SERVICE = 3;
509    private static final int TYPE_PROVIDER = 4;
510    @IntDef(prefix = { "TYPE_" }, value = {
511            TYPE_UNKNOWN,
512            TYPE_ACTIVITY,
513            TYPE_RECEIVER,
514            TYPE_SERVICE,
515            TYPE_PROVIDER,
516    })
517    @Retention(RetentionPolicy.SOURCE)
518    public @interface ComponentType {}
519
520    /**
521     * Timeout (in milliseconds) after which the watchdog should declare that
522     * our handler thread is wedged.  The usual default for such things is one
523     * minute but we sometimes do very lengthy I/O operations on this thread,
524     * such as installing multi-gigabyte applications, so ours needs to be longer.
525     */
526    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
527
528    /**
529     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
530     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
531     * settings entry if available, otherwise we use the hardcoded default.  If it's been
532     * more than this long since the last fstrim, we force one during the boot sequence.
533     *
534     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
535     * one gets run at the next available charging+idle time.  This final mandatory
536     * no-fstrim check kicks in only of the other scheduling criteria is never met.
537     */
538    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
539
540    /**
541     * Whether verification is enabled by default.
542     */
543    private static final boolean DEFAULT_VERIFY_ENABLE = true;
544
545    /**
546     * The default maximum time to wait for the verification agent to return in
547     * milliseconds.
548     */
549    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
550
551    /**
552     * The default response for package verification timeout.
553     *
554     * This can be either PackageManager.VERIFICATION_ALLOW or
555     * PackageManager.VERIFICATION_REJECT.
556     */
557    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
558
559    public static final String PLATFORM_PACKAGE_NAME = "android";
560
561    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
562
563    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
564            DEFAULT_CONTAINER_PACKAGE,
565            "com.android.defcontainer.DefaultContainerService");
566
567    private static final String KILL_APP_REASON_GIDS_CHANGED =
568            "permission grant or revoke changed gids";
569
570    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
571            "permissions revoked";
572
573    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
574
575    private static final String PACKAGE_SCHEME = "package";
576
577    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
578
579    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
580
581    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
582
583    /** Canonical intent used to identify what counts as a "web browser" app */
584    private static final Intent sBrowserIntent;
585    static {
586        sBrowserIntent = new Intent();
587        sBrowserIntent.setAction(Intent.ACTION_VIEW);
588        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
589        sBrowserIntent.setData(Uri.parse("http:"));
590        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
591    }
592
593    /**
594     * The set of all protected actions [i.e. those actions for which a high priority
595     * intent filter is disallowed].
596     */
597    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
598    static {
599        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
600        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
601        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
602        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
603    }
604
605    // Compilation reasons.
606    public static final int REASON_UNKNOWN = -1;
607    public static final int REASON_FIRST_BOOT = 0;
608    public static final int REASON_BOOT = 1;
609    public static final int REASON_INSTALL = 2;
610    public static final int REASON_BACKGROUND_DEXOPT = 3;
611    public static final int REASON_AB_OTA = 4;
612    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
613    public static final int REASON_SHARED = 6;
614
615    public static final int REASON_LAST = REASON_SHARED;
616
617    /**
618     * Version number for the package parser cache. Increment this whenever the format or
619     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
620     */
621    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
622
623    /**
624     * Whether the package parser cache is enabled.
625     */
626    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
627
628    /**
629     * Permissions required in order to receive instant application lifecycle broadcasts.
630     */
631    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
632            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
633
634    final ServiceThread mHandlerThread;
635
636    final PackageHandler mHandler;
637
638    private final ProcessLoggingHandler mProcessLoggingHandler;
639
640    /**
641     * Messages for {@link #mHandler} that need to wait for system ready before
642     * being dispatched.
643     */
644    private ArrayList<Message> mPostSystemReadyMessages;
645
646    final int mSdkVersion = Build.VERSION.SDK_INT;
647
648    final Context mContext;
649    final boolean mFactoryTest;
650    final boolean mOnlyCore;
651    final DisplayMetrics mMetrics;
652    final int mDefParseFlags;
653    final String[] mSeparateProcesses;
654    final boolean mIsUpgrade;
655    final boolean mIsPreNUpgrade;
656    final boolean mIsPreNMR1Upgrade;
657
658    // Have we told the Activity Manager to whitelist the default container service by uid yet?
659    @GuardedBy("mPackages")
660    boolean mDefaultContainerWhitelisted = false;
661
662    @GuardedBy("mPackages")
663    private boolean mDexOptDialogShown;
664
665    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
666    // LOCK HELD.  Can be called with mInstallLock held.
667    @GuardedBy("mInstallLock")
668    final Installer mInstaller;
669
670    /** Directory where installed applications are stored */
671    private static final File sAppInstallDir =
672            new File(Environment.getDataDirectory(), "app");
673    /** Directory where installed application's 32-bit native libraries are copied. */
674    private static final File sAppLib32InstallDir =
675            new File(Environment.getDataDirectory(), "app-lib");
676    /** Directory where code and non-resource assets of forward-locked applications are stored */
677    private static final File sDrmAppPrivateInstallDir =
678            new File(Environment.getDataDirectory(), "app-private");
679
680    // ----------------------------------------------------------------
681
682    // Lock for state used when installing and doing other long running
683    // operations.  Methods that must be called with this lock held have
684    // the suffix "LI".
685    final Object mInstallLock = new Object();
686
687    // ----------------------------------------------------------------
688
689    // Keys are String (package name), values are Package.  This also serves
690    // as the lock for the global state.  Methods that must be called with
691    // this lock held have the prefix "LP".
692    @GuardedBy("mPackages")
693    final ArrayMap<String, PackageParser.Package> mPackages =
694            new ArrayMap<String, PackageParser.Package>();
695
696    final ArrayMap<String, Set<String>> mKnownCodebase =
697            new ArrayMap<String, Set<String>>();
698
699    // Keys are isolated uids and values are the uid of the application
700    // that created the isolated proccess.
701    @GuardedBy("mPackages")
702    final SparseIntArray mIsolatedOwners = new SparseIntArray();
703
704    /**
705     * Tracks new system packages [received in an OTA] that we expect to
706     * find updated user-installed versions. Keys are package name, values
707     * are package location.
708     */
709    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
710    /**
711     * Tracks high priority intent filters for protected actions. During boot, certain
712     * filter actions are protected and should never be allowed to have a high priority
713     * intent filter for them. However, there is one, and only one exception -- the
714     * setup wizard. It must be able to define a high priority intent filter for these
715     * actions to ensure there are no escapes from the wizard. We need to delay processing
716     * of these during boot as we need to look at all of the system packages in order
717     * to know which component is the setup wizard.
718     */
719    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
720    /**
721     * Whether or not processing protected filters should be deferred.
722     */
723    private boolean mDeferProtectedFilters = true;
724
725    /**
726     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
727     */
728    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
729    /**
730     * Whether or not system app permissions should be promoted from install to runtime.
731     */
732    boolean mPromoteSystemApps;
733
734    @GuardedBy("mPackages")
735    final Settings mSettings;
736
737    /**
738     * Set of package names that are currently "frozen", which means active
739     * surgery is being done on the code/data for that package. The platform
740     * will refuse to launch frozen packages to avoid race conditions.
741     *
742     * @see PackageFreezer
743     */
744    @GuardedBy("mPackages")
745    final ArraySet<String> mFrozenPackages = new ArraySet<>();
746
747    final ProtectedPackages mProtectedPackages;
748
749    @GuardedBy("mLoadedVolumes")
750    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
751
752    boolean mFirstBoot;
753
754    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
755
756    @GuardedBy("mAvailableFeatures")
757    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
758
759    private final InstantAppRegistry mInstantAppRegistry;
760
761    @GuardedBy("mPackages")
762    int mChangedPackagesSequenceNumber;
763    /**
764     * List of changed [installed, removed or updated] packages.
765     * mapping from user id -> sequence number -> package name
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
769    /**
770     * The sequence number of the last change to a package.
771     * mapping from user id -> package name -> sequence number
772     */
773    @GuardedBy("mPackages")
774    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
775
776    @GuardedBy("mPackages")
777    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
778
779    class PackageParserCallback implements PackageParser.Callback {
780        @Override public final boolean hasFeature(String feature) {
781            return PackageManagerService.this.hasSystemFeature(feature, 0);
782        }
783
784        final List<PackageParser.Package> getStaticOverlayPackages(
785                Collection<PackageParser.Package> allPackages, String targetPackageName) {
786            if ("android".equals(targetPackageName)) {
787                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
788                // native AssetManager.
789                return null;
790            }
791
792            List<PackageParser.Package> overlayPackages = null;
793            for (PackageParser.Package p : allPackages) {
794                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
795                    if (overlayPackages == null) {
796                        overlayPackages = new ArrayList<PackageParser.Package>();
797                    }
798                    overlayPackages.add(p);
799                }
800            }
801            if (overlayPackages != null) {
802                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
803                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
804                        return p1.mOverlayPriority - p2.mOverlayPriority;
805                    }
806                };
807                Collections.sort(overlayPackages, cmp);
808            }
809            return overlayPackages;
810        }
811
812        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
813                String targetPath) {
814            if (overlayPackages == null || overlayPackages.isEmpty()) {
815                return null;
816            }
817            List<String> overlayPathList = null;
818            for (PackageParser.Package overlayPackage : overlayPackages) {
819                if (targetPath == null) {
820                    if (overlayPathList == null) {
821                        overlayPathList = new ArrayList<String>();
822                    }
823                    overlayPathList.add(overlayPackage.baseCodePath);
824                    continue;
825                }
826
827                try {
828                    // Creates idmaps for system to parse correctly the Android manifest of the
829                    // target package.
830                    //
831                    // OverlayManagerService will update each of them with a correct gid from its
832                    // target package app id.
833                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
834                            UserHandle.getSharedAppGid(
835                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
836                    if (overlayPathList == null) {
837                        overlayPathList = new ArrayList<String>();
838                    }
839                    overlayPathList.add(overlayPackage.baseCodePath);
840                } catch (InstallerException e) {
841                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
842                            overlayPackage.baseCodePath);
843                }
844            }
845            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
846        }
847
848        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
849            List<PackageParser.Package> overlayPackages;
850            synchronized (mInstallLock) {
851                synchronized (mPackages) {
852                    overlayPackages = getStaticOverlayPackages(
853                            mPackages.values(), targetPackageName);
854                }
855                // It is safe to keep overlayPackages without holding mPackages because static overlay
856                // packages can't be uninstalled or disabled.
857                return getStaticOverlayPaths(overlayPackages, targetPath);
858            }
859        }
860
861        @Override public final String[] getOverlayApks(String targetPackageName) {
862            return getStaticOverlayPaths(targetPackageName, null);
863        }
864
865        @Override public final String[] getOverlayPaths(String targetPackageName,
866                String targetPath) {
867            return getStaticOverlayPaths(targetPackageName, targetPath);
868        }
869    }
870
871    class ParallelPackageParserCallback extends PackageParserCallback {
872        List<PackageParser.Package> mOverlayPackages = null;
873
874        void findStaticOverlayPackages() {
875            synchronized (mPackages) {
876                for (PackageParser.Package p : mPackages.values()) {
877                    if (p.mOverlayIsStatic) {
878                        if (mOverlayPackages == null) {
879                            mOverlayPackages = new ArrayList<PackageParser.Package>();
880                        }
881                        mOverlayPackages.add(p);
882                    }
883                }
884            }
885        }
886
887        @Override
888        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
889            // We can trust mOverlayPackages without holding mPackages because package uninstall
890            // can't happen while running parallel parsing.
891            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
892            // because mInstallLock is held before running parallel parsing.
893            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
894            return mOverlayPackages == null ? null :
895                    getStaticOverlayPaths(
896                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
897                            targetPath);
898        }
899    }
900
901    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
902    final ParallelPackageParserCallback mParallelPackageParserCallback =
903            new ParallelPackageParserCallback();
904
905    public static final class SharedLibraryEntry {
906        public final @Nullable String path;
907        public final @Nullable String apk;
908        public final @NonNull SharedLibraryInfo info;
909
910        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
911                String declaringPackageName, long declaringPackageVersionCode) {
912            path = _path;
913            apk = _apk;
914            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
915                    declaringPackageName, declaringPackageVersionCode), null);
916        }
917    }
918
919    // Currently known shared libraries.
920    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
921    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
922            new ArrayMap<>();
923
924    // All available activities, for your resolving pleasure.
925    final ActivityIntentResolver mActivities =
926            new ActivityIntentResolver();
927
928    // All available receivers, for your resolving pleasure.
929    final ActivityIntentResolver mReceivers =
930            new ActivityIntentResolver();
931
932    // All available services, for your resolving pleasure.
933    final ServiceIntentResolver mServices = new ServiceIntentResolver();
934
935    // All available providers, for your resolving pleasure.
936    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
937
938    // Mapping from provider base names (first directory in content URI codePath)
939    // to the provider information.
940    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
941            new ArrayMap<String, PackageParser.Provider>();
942
943    // Mapping from instrumentation class names to info about them.
944    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
945            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
946
947    // Packages whose data we have transfered into another package, thus
948    // should no longer exist.
949    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
950
951    // Broadcast actions that are only available to the system.
952    @GuardedBy("mProtectedBroadcasts")
953    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
954
955    /** List of packages waiting for verification. */
956    final SparseArray<PackageVerificationState> mPendingVerification
957            = new SparseArray<PackageVerificationState>();
958
959    final PackageInstallerService mInstallerService;
960
961    final ArtManagerService mArtManagerService;
962
963    private final PackageDexOptimizer mPackageDexOptimizer;
964    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
965    // is used by other apps).
966    private final DexManager mDexManager;
967
968    private AtomicInteger mNextMoveId = new AtomicInteger();
969    private final MoveCallbacks mMoveCallbacks;
970
971    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
972
973    // Cache of users who need badging.
974    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
975
976    /** Token for keys in mPendingVerification. */
977    private int mPendingVerificationToken = 0;
978
979    volatile boolean mSystemReady;
980    volatile boolean mSafeMode;
981    volatile boolean mHasSystemUidErrors;
982    private volatile boolean mWebInstantAppsDisabled;
983
984    ApplicationInfo mAndroidApplication;
985    final ActivityInfo mResolveActivity = new ActivityInfo();
986    final ResolveInfo mResolveInfo = new ResolveInfo();
987    ComponentName mResolveComponentName;
988    PackageParser.Package mPlatformPackage;
989    ComponentName mCustomResolverComponentName;
990
991    boolean mResolverReplaced = false;
992
993    private final @Nullable ComponentName mIntentFilterVerifierComponent;
994    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
995
996    private int mIntentFilterVerificationToken = 0;
997
998    /** The service connection to the ephemeral resolver */
999    final InstantAppResolverConnection mInstantAppResolverConnection;
1000    /** Component used to show resolver settings for Instant Apps */
1001    final ComponentName mInstantAppResolverSettingsComponent;
1002
1003    /** Activity used to install instant applications */
1004    ActivityInfo mInstantAppInstallerActivity;
1005    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1006
1007    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1008            = new SparseArray<IntentFilterVerificationState>();
1009
1010    // TODO remove this and go through mPermissonManager directly
1011    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1012    private final PermissionManagerInternal mPermissionManager;
1013
1014    // List of packages names to keep cached, even if they are uninstalled for all users
1015    private List<String> mKeepUninstalledPackages;
1016
1017    private UserManagerInternal mUserManagerInternal;
1018    private ActivityManagerInternal mActivityManagerInternal;
1019
1020    private DeviceIdleController.LocalService mDeviceIdleController;
1021
1022    private File mCacheDir;
1023
1024    private Future<?> mPrepareAppDataFuture;
1025
1026    private static class IFVerificationParams {
1027        PackageParser.Package pkg;
1028        boolean replacing;
1029        int userId;
1030        int verifierUid;
1031
1032        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1033                int _userId, int _verifierUid) {
1034            pkg = _pkg;
1035            replacing = _replacing;
1036            userId = _userId;
1037            replacing = _replacing;
1038            verifierUid = _verifierUid;
1039        }
1040    }
1041
1042    private interface IntentFilterVerifier<T extends IntentFilter> {
1043        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1044                                               T filter, String packageName);
1045        void startVerifications(int userId);
1046        void receiveVerificationResponse(int verificationId);
1047    }
1048
1049    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1050        private Context mContext;
1051        private ComponentName mIntentFilterVerifierComponent;
1052        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1053
1054        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1055            mContext = context;
1056            mIntentFilterVerifierComponent = verifierComponent;
1057        }
1058
1059        private String getDefaultScheme() {
1060            return IntentFilter.SCHEME_HTTPS;
1061        }
1062
1063        @Override
1064        public void startVerifications(int userId) {
1065            // Launch verifications requests
1066            int count = mCurrentIntentFilterVerifications.size();
1067            for (int n=0; n<count; n++) {
1068                int verificationId = mCurrentIntentFilterVerifications.get(n);
1069                final IntentFilterVerificationState ivs =
1070                        mIntentFilterVerificationStates.get(verificationId);
1071
1072                String packageName = ivs.getPackageName();
1073
1074                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1075                final int filterCount = filters.size();
1076                ArraySet<String> domainsSet = new ArraySet<>();
1077                for (int m=0; m<filterCount; m++) {
1078                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1079                    domainsSet.addAll(filter.getHostsList());
1080                }
1081                synchronized (mPackages) {
1082                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1083                            packageName, domainsSet) != null) {
1084                        scheduleWriteSettingsLocked();
1085                    }
1086                }
1087                sendVerificationRequest(verificationId, ivs);
1088            }
1089            mCurrentIntentFilterVerifications.clear();
1090        }
1091
1092        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1093            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1096                    verificationId);
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1099                    getDefaultScheme());
1100            verificationIntent.putExtra(
1101                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1102                    ivs.getHostsString());
1103            verificationIntent.putExtra(
1104                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1105                    ivs.getPackageName());
1106            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1107            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1108
1109            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1110            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1111                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1112                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1113
1114            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1115            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1116                    "Sending IntentFilter verification broadcast");
1117        }
1118
1119        public void receiveVerificationResponse(int verificationId) {
1120            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1121
1122            final boolean verified = ivs.isVerified();
1123
1124            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1125            final int count = filters.size();
1126            if (DEBUG_DOMAIN_VERIFICATION) {
1127                Slog.i(TAG, "Received verification response " + verificationId
1128                        + " for " + count + " filters, verified=" + verified);
1129            }
1130            for (int n=0; n<count; n++) {
1131                PackageParser.ActivityIntentInfo filter = filters.get(n);
1132                filter.setVerified(verified);
1133
1134                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1135                        + " verified with result:" + verified + " and hosts:"
1136                        + ivs.getHostsString());
1137            }
1138
1139            mIntentFilterVerificationStates.remove(verificationId);
1140
1141            final String packageName = ivs.getPackageName();
1142            IntentFilterVerificationInfo ivi = null;
1143
1144            synchronized (mPackages) {
1145                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1146            }
1147            if (ivi == null) {
1148                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1149                        + verificationId + " packageName:" + packageName);
1150                return;
1151            }
1152            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1153                    "Updating IntentFilterVerificationInfo for package " + packageName
1154                            +" verificationId:" + verificationId);
1155
1156            synchronized (mPackages) {
1157                if (verified) {
1158                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1159                } else {
1160                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1161                }
1162                scheduleWriteSettingsLocked();
1163
1164                final int userId = ivs.getUserId();
1165                if (userId != UserHandle.USER_ALL) {
1166                    final int userStatus =
1167                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1168
1169                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1170                    boolean needUpdate = false;
1171
1172                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1173                    // already been set by the User thru the Disambiguation dialog
1174                    switch (userStatus) {
1175                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1176                            if (verified) {
1177                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1178                            } else {
1179                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1180                            }
1181                            needUpdate = true;
1182                            break;
1183
1184                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1185                            if (verified) {
1186                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1187                                needUpdate = true;
1188                            }
1189                            break;
1190
1191                        default:
1192                            // Nothing to do
1193                    }
1194
1195                    if (needUpdate) {
1196                        mSettings.updateIntentFilterVerificationStatusLPw(
1197                                packageName, updatedStatus, userId);
1198                        scheduleWritePackageRestrictionsLocked(userId);
1199                    }
1200                }
1201            }
1202        }
1203
1204        @Override
1205        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1206                    ActivityIntentInfo filter, String packageName) {
1207            if (!hasValidDomains(filter)) {
1208                return false;
1209            }
1210            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1211            if (ivs == null) {
1212                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1213                        packageName);
1214            }
1215            if (DEBUG_DOMAIN_VERIFICATION) {
1216                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1217            }
1218            ivs.addFilter(filter);
1219            return true;
1220        }
1221
1222        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1223                int userId, int verificationId, String packageName) {
1224            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1225                    verifierUid, userId, packageName);
1226            ivs.setPendingState();
1227            synchronized (mPackages) {
1228                mIntentFilterVerificationStates.append(verificationId, ivs);
1229                mCurrentIntentFilterVerifications.add(verificationId);
1230            }
1231            return ivs;
1232        }
1233    }
1234
1235    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1236        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1237                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1238                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1239    }
1240
1241    // Set of pending broadcasts for aggregating enable/disable of components.
1242    static class PendingPackageBroadcasts {
1243        // for each user id, a map of <package name -> components within that package>
1244        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1245
1246        public PendingPackageBroadcasts() {
1247            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1248        }
1249
1250        public ArrayList<String> get(int userId, String packageName) {
1251            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1252            return packages.get(packageName);
1253        }
1254
1255        public void put(int userId, String packageName, ArrayList<String> components) {
1256            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1257            packages.put(packageName, components);
1258        }
1259
1260        public void remove(int userId, String packageName) {
1261            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1262            if (packages != null) {
1263                packages.remove(packageName);
1264            }
1265        }
1266
1267        public void remove(int userId) {
1268            mUidMap.remove(userId);
1269        }
1270
1271        public int userIdCount() {
1272            return mUidMap.size();
1273        }
1274
1275        public int userIdAt(int n) {
1276            return mUidMap.keyAt(n);
1277        }
1278
1279        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1280            return mUidMap.get(userId);
1281        }
1282
1283        public int size() {
1284            // total number of pending broadcast entries across all userIds
1285            int num = 0;
1286            for (int i = 0; i< mUidMap.size(); i++) {
1287                num += mUidMap.valueAt(i).size();
1288            }
1289            return num;
1290        }
1291
1292        public void clear() {
1293            mUidMap.clear();
1294        }
1295
1296        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1297            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1298            if (map == null) {
1299                map = new ArrayMap<String, ArrayList<String>>();
1300                mUidMap.put(userId, map);
1301            }
1302            return map;
1303        }
1304    }
1305    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1306
1307    // Service Connection to remote media container service to copy
1308    // package uri's from external media onto secure containers
1309    // or internal storage.
1310    private IMediaContainerService mContainerService = null;
1311
1312    static final int SEND_PENDING_BROADCAST = 1;
1313    static final int MCS_BOUND = 3;
1314    static final int END_COPY = 4;
1315    static final int INIT_COPY = 5;
1316    static final int MCS_UNBIND = 6;
1317    static final int START_CLEANING_PACKAGE = 7;
1318    static final int FIND_INSTALL_LOC = 8;
1319    static final int POST_INSTALL = 9;
1320    static final int MCS_RECONNECT = 10;
1321    static final int MCS_GIVE_UP = 11;
1322    static final int WRITE_SETTINGS = 13;
1323    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1324    static final int PACKAGE_VERIFIED = 15;
1325    static final int CHECK_PENDING_VERIFICATION = 16;
1326    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1327    static final int INTENT_FILTER_VERIFIED = 18;
1328    static final int WRITE_PACKAGE_LIST = 19;
1329    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1330    static final int DEF_CONTAINER_BIND = 21;
1331
1332    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1333
1334    // Delay time in millisecs
1335    static final int BROADCAST_DELAY = 10 * 1000;
1336
1337    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1338            2 * 60 * 60 * 1000L; /* two hours */
1339
1340    static UserManagerService sUserManager;
1341
1342    // Stores a list of users whose package restrictions file needs to be updated
1343    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1344
1345    final private DefaultContainerConnection mDefContainerConn =
1346            new DefaultContainerConnection();
1347    class DefaultContainerConnection implements ServiceConnection {
1348        public void onServiceConnected(ComponentName name, IBinder service) {
1349            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1350            final IMediaContainerService imcs = IMediaContainerService.Stub
1351                    .asInterface(Binder.allowBlocking(service));
1352            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1353        }
1354
1355        public void onServiceDisconnected(ComponentName name) {
1356            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1357        }
1358    }
1359
1360    // Recordkeeping of restore-after-install operations that are currently in flight
1361    // between the Package Manager and the Backup Manager
1362    static class PostInstallData {
1363        public InstallArgs args;
1364        public PackageInstalledInfo res;
1365
1366        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1367            args = _a;
1368            res = _r;
1369        }
1370    }
1371
1372    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1373    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1374
1375    // XML tags for backup/restore of various bits of state
1376    private static final String TAG_PREFERRED_BACKUP = "pa";
1377    private static final String TAG_DEFAULT_APPS = "da";
1378    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1379
1380    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1381    private static final String TAG_ALL_GRANTS = "rt-grants";
1382    private static final String TAG_GRANT = "grant";
1383    private static final String ATTR_PACKAGE_NAME = "pkg";
1384
1385    private static final String TAG_PERMISSION = "perm";
1386    private static final String ATTR_PERMISSION_NAME = "name";
1387    private static final String ATTR_IS_GRANTED = "g";
1388    private static final String ATTR_USER_SET = "set";
1389    private static final String ATTR_USER_FIXED = "fixed";
1390    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1391
1392    // System/policy permission grants are not backed up
1393    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1394            FLAG_PERMISSION_POLICY_FIXED
1395            | FLAG_PERMISSION_SYSTEM_FIXED
1396            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1397
1398    // And we back up these user-adjusted states
1399    private static final int USER_RUNTIME_GRANT_MASK =
1400            FLAG_PERMISSION_USER_SET
1401            | FLAG_PERMISSION_USER_FIXED
1402            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1403
1404    final @Nullable String mRequiredVerifierPackage;
1405    final @NonNull String mRequiredInstallerPackage;
1406    final @NonNull String mRequiredUninstallerPackage;
1407    final @Nullable String mSetupWizardPackage;
1408    final @Nullable String mStorageManagerPackage;
1409    final @Nullable String mSystemTextClassifierPackage;
1410    final @NonNull String mServicesSystemSharedLibraryPackageName;
1411    final @NonNull String mSharedSystemSharedLibraryPackageName;
1412
1413    private final PackageUsage mPackageUsage = new PackageUsage();
1414    private final CompilerStats mCompilerStats = new CompilerStats();
1415
1416    class PackageHandler extends Handler {
1417        private boolean mBound = false;
1418        final ArrayList<HandlerParams> mPendingInstalls =
1419            new ArrayList<HandlerParams>();
1420
1421        private boolean connectToService() {
1422            if (DEBUG_INSTALL) Log.i(TAG, "Trying to bind to DefaultContainerService");
1423            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1425            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1426                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1427                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428                mBound = true;
1429                return true;
1430            }
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432            return false;
1433        }
1434
1435        private void disconnectService() {
1436            mContainerService = null;
1437            mBound = false;
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1439            mContext.unbindService(mDefContainerConn);
1440            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441        }
1442
1443        PackageHandler(Looper looper) {
1444            super(looper);
1445        }
1446
1447        public void handleMessage(Message msg) {
1448            try {
1449                doHandleMessage(msg);
1450            } finally {
1451                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1452            }
1453        }
1454
1455        void doHandleMessage(Message msg) {
1456            switch (msg.what) {
1457                case DEF_CONTAINER_BIND:
1458                    if (!mBound) {
1459                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1460                                System.identityHashCode(mHandler));
1461                        if (!connectToService()) {
1462                            Slog.e(TAG, "Failed to bind to media container service");
1463                        }
1464                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "earlyBindingMCS",
1465                                System.identityHashCode(mHandler));
1466                    }
1467                    break;
1468                case INIT_COPY: {
1469                    HandlerParams params = (HandlerParams) msg.obj;
1470                    int idx = mPendingInstalls.size();
1471                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1472                    // If a bind was already initiated we dont really
1473                    // need to do anything. The pending install
1474                    // will be processed later on.
1475                    if (!mBound) {
1476                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1477                                System.identityHashCode(mHandler));
1478                        // If this is the only one pending we might
1479                        // have to bind to the service again.
1480                        if (!connectToService()) {
1481                            Slog.e(TAG, "Failed to bind to media container service");
1482                            params.serviceError();
1483                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1484                                    System.identityHashCode(mHandler));
1485                            if (params.traceMethod != null) {
1486                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1487                                        params.traceCookie);
1488                            }
1489                            return;
1490                        } else {
1491                            // Once we bind to the service, the first
1492                            // pending request will be processed.
1493                            mPendingInstalls.add(idx, params);
1494                        }
1495                    } else {
1496                        mPendingInstalls.add(idx, params);
1497                        // Already bound to the service. Just make
1498                        // sure we trigger off processing the first request.
1499                        if (idx == 0) {
1500                            mHandler.sendEmptyMessage(MCS_BOUND);
1501                        }
1502                    }
1503                    break;
1504                }
1505                case MCS_BOUND: {
1506                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1507                    if (msg.obj != null) {
1508                        mContainerService = (IMediaContainerService) msg.obj;
1509                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1510                                System.identityHashCode(mHandler));
1511                    }
1512                    if (mContainerService == null) {
1513                        if (!mBound) {
1514                            // Something seriously wrong since we are not bound and we are not
1515                            // waiting for connection. Bail out.
1516                            Slog.e(TAG, "Cannot bind to media container service");
1517                            for (HandlerParams params : mPendingInstalls) {
1518                                // Indicate service bind error
1519                                params.serviceError();
1520                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1521                                        System.identityHashCode(params));
1522                                if (params.traceMethod != null) {
1523                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1524                                            params.traceMethod, params.traceCookie);
1525                                }
1526                            }
1527                            mPendingInstalls.clear();
1528                        } else {
1529                            Slog.w(TAG, "Waiting to connect to media container service");
1530                        }
1531                    } else if (mPendingInstalls.size() > 0) {
1532                        HandlerParams params = mPendingInstalls.get(0);
1533                        if (params != null) {
1534                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1535                                    System.identityHashCode(params));
1536                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1537                            if (params.startCopy()) {
1538                                // We are done...  look for more work or to
1539                                // go idle.
1540                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1541                                        "Checking for more work or unbind...");
1542                                // Delete pending install
1543                                if (mPendingInstalls.size() > 0) {
1544                                    mPendingInstalls.remove(0);
1545                                }
1546                                if (mPendingInstalls.size() == 0) {
1547                                    if (mBound) {
1548                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1549                                                "Posting delayed MCS_UNBIND");
1550                                        removeMessages(MCS_UNBIND);
1551                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1552                                        // Unbind after a little delay, to avoid
1553                                        // continual thrashing.
1554                                        sendMessageDelayed(ubmsg, 10000);
1555                                    }
1556                                } else {
1557                                    // There are more pending requests in queue.
1558                                    // Just post MCS_BOUND message to trigger processing
1559                                    // of next pending install.
1560                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1561                                            "Posting MCS_BOUND for next work");
1562                                    mHandler.sendEmptyMessage(MCS_BOUND);
1563                                }
1564                            }
1565                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1566                        }
1567                    } else {
1568                        // Should never happen ideally.
1569                        Slog.w(TAG, "Empty queue");
1570                    }
1571                    break;
1572                }
1573                case MCS_RECONNECT: {
1574                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1575                    if (mPendingInstalls.size() > 0) {
1576                        if (mBound) {
1577                            disconnectService();
1578                        }
1579                        if (!connectToService()) {
1580                            Slog.e(TAG, "Failed to bind to media container service");
1581                            for (HandlerParams params : mPendingInstalls) {
1582                                // Indicate service bind error
1583                                params.serviceError();
1584                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1585                                        System.identityHashCode(params));
1586                            }
1587                            mPendingInstalls.clear();
1588                        }
1589                    }
1590                    break;
1591                }
1592                case MCS_UNBIND: {
1593                    // If there is no actual work left, then time to unbind.
1594                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1595
1596                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1597                        if (mBound) {
1598                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1599
1600                            disconnectService();
1601                        }
1602                    } else if (mPendingInstalls.size() > 0) {
1603                        // There are more pending requests in queue.
1604                        // Just post MCS_BOUND message to trigger processing
1605                        // of next pending install.
1606                        mHandler.sendEmptyMessage(MCS_BOUND);
1607                    }
1608
1609                    break;
1610                }
1611                case MCS_GIVE_UP: {
1612                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1613                    HandlerParams params = mPendingInstalls.remove(0);
1614                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1615                            System.identityHashCode(params));
1616                    break;
1617                }
1618                case SEND_PENDING_BROADCAST: {
1619                    String packages[];
1620                    ArrayList<String> components[];
1621                    int size = 0;
1622                    int uids[];
1623                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1624                    synchronized (mPackages) {
1625                        if (mPendingBroadcasts == null) {
1626                            return;
1627                        }
1628                        size = mPendingBroadcasts.size();
1629                        if (size <= 0) {
1630                            // Nothing to be done. Just return
1631                            return;
1632                        }
1633                        packages = new String[size];
1634                        components = new ArrayList[size];
1635                        uids = new int[size];
1636                        int i = 0;  // filling out the above arrays
1637
1638                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1639                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1640                            Iterator<Map.Entry<String, ArrayList<String>>> it
1641                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1642                                            .entrySet().iterator();
1643                            while (it.hasNext() && i < size) {
1644                                Map.Entry<String, ArrayList<String>> ent = it.next();
1645                                packages[i] = ent.getKey();
1646                                components[i] = ent.getValue();
1647                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1648                                uids[i] = (ps != null)
1649                                        ? UserHandle.getUid(packageUserId, ps.appId)
1650                                        : -1;
1651                                i++;
1652                            }
1653                        }
1654                        size = i;
1655                        mPendingBroadcasts.clear();
1656                    }
1657                    // Send broadcasts
1658                    for (int i = 0; i < size; i++) {
1659                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1660                    }
1661                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1662                    break;
1663                }
1664                case START_CLEANING_PACKAGE: {
1665                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1666                    final String packageName = (String)msg.obj;
1667                    final int userId = msg.arg1;
1668                    final boolean andCode = msg.arg2 != 0;
1669                    synchronized (mPackages) {
1670                        if (userId == UserHandle.USER_ALL) {
1671                            int[] users = sUserManager.getUserIds();
1672                            for (int user : users) {
1673                                mSettings.addPackageToCleanLPw(
1674                                        new PackageCleanItem(user, packageName, andCode));
1675                            }
1676                        } else {
1677                            mSettings.addPackageToCleanLPw(
1678                                    new PackageCleanItem(userId, packageName, andCode));
1679                        }
1680                    }
1681                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1682                    startCleaningPackages();
1683                } break;
1684                case POST_INSTALL: {
1685                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1686
1687                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1688                    final boolean didRestore = (msg.arg2 != 0);
1689                    mRunningInstalls.delete(msg.arg1);
1690
1691                    if (data != null) {
1692                        InstallArgs args = data.args;
1693                        PackageInstalledInfo parentRes = data.res;
1694
1695                        final boolean grantPermissions = (args.installFlags
1696                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1697                        final boolean killApp = (args.installFlags
1698                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1699                        final boolean virtualPreload = ((args.installFlags
1700                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1701                        final String[] grantedPermissions = args.installGrantPermissions;
1702
1703                        // Handle the parent package
1704                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1705                                virtualPreload, grantedPermissions, didRestore,
1706                                args.installerPackageName, args.observer);
1707
1708                        // Handle the child packages
1709                        final int childCount = (parentRes.addedChildPackages != null)
1710                                ? parentRes.addedChildPackages.size() : 0;
1711                        for (int i = 0; i < childCount; i++) {
1712                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1713                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1714                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1715                                    args.installerPackageName, args.observer);
1716                        }
1717
1718                        // Log tracing if needed
1719                        if (args.traceMethod != null) {
1720                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1721                                    args.traceCookie);
1722                        }
1723                    } else {
1724                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1725                    }
1726
1727                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1728                } break;
1729                case WRITE_SETTINGS: {
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731                    synchronized (mPackages) {
1732                        removeMessages(WRITE_SETTINGS);
1733                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1734                        mSettings.writeLPr();
1735                        mDirtyUsers.clear();
1736                    }
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1738                } break;
1739                case WRITE_PACKAGE_RESTRICTIONS: {
1740                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1741                    synchronized (mPackages) {
1742                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1743                        for (int userId : mDirtyUsers) {
1744                            mSettings.writePackageRestrictionsLPr(userId);
1745                        }
1746                        mDirtyUsers.clear();
1747                    }
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1749                } break;
1750                case WRITE_PACKAGE_LIST: {
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1752                    synchronized (mPackages) {
1753                        removeMessages(WRITE_PACKAGE_LIST);
1754                        mSettings.writePackageListLPr(msg.arg1);
1755                    }
1756                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1757                } break;
1758                case CHECK_PENDING_VERIFICATION: {
1759                    final int verificationId = msg.arg1;
1760                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1761
1762                    if ((state != null) && !state.timeoutExtended()) {
1763                        final InstallArgs args = state.getInstallArgs();
1764                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1765
1766                        Slog.i(TAG, "Verification timed out for " + originUri);
1767                        mPendingVerification.remove(verificationId);
1768
1769                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1770
1771                        final UserHandle user = args.getUser();
1772                        if (getDefaultVerificationResponse(user)
1773                                == PackageManager.VERIFICATION_ALLOW) {
1774                            Slog.i(TAG, "Continuing with installation of " + originUri);
1775                            state.setVerifierResponse(Binder.getCallingUid(),
1776                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1777                            broadcastPackageVerified(verificationId, originUri,
1778                                    PackageManager.VERIFICATION_ALLOW, user);
1779                            try {
1780                                ret = args.copyApk(mContainerService, true);
1781                            } catch (RemoteException e) {
1782                                Slog.e(TAG, "Could not contact the ContainerService");
1783                            }
1784                        } else {
1785                            broadcastPackageVerified(verificationId, originUri,
1786                                    PackageManager.VERIFICATION_REJECT, user);
1787                        }
1788
1789                        Trace.asyncTraceEnd(
1790                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1791
1792                        processPendingInstall(args, ret);
1793                        mHandler.sendEmptyMessage(MCS_UNBIND);
1794                    }
1795                    break;
1796                }
1797                case PACKAGE_VERIFIED: {
1798                    final int verificationId = msg.arg1;
1799
1800                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1801                    if (state == null) {
1802                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1803                        break;
1804                    }
1805
1806                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1807
1808                    state.setVerifierResponse(response.callerUid, response.code);
1809
1810                    if (state.isVerificationComplete()) {
1811                        mPendingVerification.remove(verificationId);
1812
1813                        final InstallArgs args = state.getInstallArgs();
1814                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1815
1816                        int ret;
1817                        if (state.isInstallAllowed()) {
1818                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1819                            broadcastPackageVerified(verificationId, originUri,
1820                                    response.code, state.getInstallArgs().getUser());
1821                            try {
1822                                ret = args.copyApk(mContainerService, true);
1823                            } catch (RemoteException e) {
1824                                Slog.e(TAG, "Could not contact the ContainerService");
1825                            }
1826                        } else {
1827                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1828                        }
1829
1830                        Trace.asyncTraceEnd(
1831                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1832
1833                        processPendingInstall(args, ret);
1834                        mHandler.sendEmptyMessage(MCS_UNBIND);
1835                    }
1836
1837                    break;
1838                }
1839                case START_INTENT_FILTER_VERIFICATIONS: {
1840                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1841                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1842                            params.replacing, params.pkg);
1843                    break;
1844                }
1845                case INTENT_FILTER_VERIFIED: {
1846                    final int verificationId = msg.arg1;
1847
1848                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1849                            verificationId);
1850                    if (state == null) {
1851                        Slog.w(TAG, "Invalid IntentFilter verification token "
1852                                + verificationId + " received");
1853                        break;
1854                    }
1855
1856                    final int userId = state.getUserId();
1857
1858                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1859                            "Processing IntentFilter verification with token:"
1860                            + verificationId + " and userId:" + userId);
1861
1862                    final IntentFilterVerificationResponse response =
1863                            (IntentFilterVerificationResponse) msg.obj;
1864
1865                    state.setVerifierResponse(response.callerUid, response.code);
1866
1867                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1868                            "IntentFilter verification with token:" + verificationId
1869                            + " and userId:" + userId
1870                            + " is settings verifier response with response code:"
1871                            + response.code);
1872
1873                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1874                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1875                                + response.getFailedDomainsString());
1876                    }
1877
1878                    if (state.isVerificationComplete()) {
1879                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1880                    } else {
1881                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1882                                "IntentFilter verification with token:" + verificationId
1883                                + " was not said to be complete");
1884                    }
1885
1886                    break;
1887                }
1888                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1889                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1890                            mInstantAppResolverConnection,
1891                            (InstantAppRequest) msg.obj,
1892                            mInstantAppInstallerActivity,
1893                            mHandler);
1894                }
1895            }
1896        }
1897    }
1898
1899    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1900        @Override
1901        public void onGidsChanged(int appId, int userId) {
1902            mHandler.post(new Runnable() {
1903                @Override
1904                public void run() {
1905                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1906                }
1907            });
1908        }
1909        @Override
1910        public void onPermissionGranted(int uid, int userId) {
1911            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1912
1913            // Not critical; if this is lost, the application has to request again.
1914            synchronized (mPackages) {
1915                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1916            }
1917        }
1918        @Override
1919        public void onInstallPermissionGranted() {
1920            synchronized (mPackages) {
1921                scheduleWriteSettingsLocked();
1922            }
1923        }
1924        @Override
1925        public void onPermissionRevoked(int uid, int userId) {
1926            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1927
1928            synchronized (mPackages) {
1929                // Critical; after this call the application should never have the permission
1930                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1931            }
1932
1933            final int appId = UserHandle.getAppId(uid);
1934            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1935        }
1936        @Override
1937        public void onInstallPermissionRevoked() {
1938            synchronized (mPackages) {
1939                scheduleWriteSettingsLocked();
1940            }
1941        }
1942        @Override
1943        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1944            synchronized (mPackages) {
1945                for (int userId : updatedUserIds) {
1946                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1947                }
1948            }
1949        }
1950        @Override
1951        public void onInstallPermissionUpdated() {
1952            synchronized (mPackages) {
1953                scheduleWriteSettingsLocked();
1954            }
1955        }
1956        @Override
1957        public void onPermissionRemoved() {
1958            synchronized (mPackages) {
1959                mSettings.writeLPr();
1960            }
1961        }
1962    };
1963
1964    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1965            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1966            boolean launchedForRestore, String installerPackage,
1967            IPackageInstallObserver2 installObserver) {
1968        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1969            // Send the removed broadcasts
1970            if (res.removedInfo != null) {
1971                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1972            }
1973
1974            // Now that we successfully installed the package, grant runtime
1975            // permissions if requested before broadcasting the install. Also
1976            // for legacy apps in permission review mode we clear the permission
1977            // review flag which is used to emulate runtime permissions for
1978            // legacy apps.
1979            if (grantPermissions) {
1980                final int callingUid = Binder.getCallingUid();
1981                mPermissionManager.grantRequestedRuntimePermissions(
1982                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1983                        mPermissionCallback);
1984            }
1985
1986            final boolean update = res.removedInfo != null
1987                    && res.removedInfo.removedPackage != null;
1988            final String installerPackageName =
1989                    res.installerPackageName != null
1990                            ? res.installerPackageName
1991                            : res.removedInfo != null
1992                                    ? res.removedInfo.installerPackageName
1993                                    : null;
1994
1995            // If this is the first time we have child packages for a disabled privileged
1996            // app that had no children, we grant requested runtime permissions to the new
1997            // children if the parent on the system image had them already granted.
1998            if (res.pkg.parentPackage != null) {
1999                final int callingUid = Binder.getCallingUid();
2000                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2001                        res.pkg, callingUid, mPermissionCallback);
2002            }
2003
2004            synchronized (mPackages) {
2005                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2006            }
2007
2008            final String packageName = res.pkg.applicationInfo.packageName;
2009
2010            // Determine the set of users who are adding this package for
2011            // the first time vs. those who are seeing an update.
2012            int[] firstUserIds = EMPTY_INT_ARRAY;
2013            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2014            int[] updateUserIds = EMPTY_INT_ARRAY;
2015            int[] instantUserIds = EMPTY_INT_ARRAY;
2016            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2017            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2018            for (int newUser : res.newUsers) {
2019                final boolean isInstantApp = ps.getInstantApp(newUser);
2020                if (allNewUsers) {
2021                    if (isInstantApp) {
2022                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2023                    } else {
2024                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2025                    }
2026                    continue;
2027                }
2028                boolean isNew = true;
2029                for (int origUser : res.origUsers) {
2030                    if (origUser == newUser) {
2031                        isNew = false;
2032                        break;
2033                    }
2034                }
2035                if (isNew) {
2036                    if (isInstantApp) {
2037                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2038                    } else {
2039                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2040                    }
2041                } else {
2042                    if (isInstantApp) {
2043                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2044                    } else {
2045                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2046                    }
2047                }
2048            }
2049
2050            // Send installed broadcasts if the package is not a static shared lib.
2051            if (res.pkg.staticSharedLibName == null) {
2052                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2053
2054                // Send added for users that see the package for the first time
2055                // sendPackageAddedForNewUsers also deals with system apps
2056                int appId = UserHandle.getAppId(res.uid);
2057                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2058                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2059                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2060
2061                // Send added for users that don't see the package for the first time
2062                Bundle extras = new Bundle(1);
2063                extras.putInt(Intent.EXTRA_UID, res.uid);
2064                if (update) {
2065                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2066                }
2067                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2068                        extras, 0 /*flags*/,
2069                        null /*targetPackage*/, null /*finishedReceiver*/,
2070                        updateUserIds, instantUserIds);
2071                if (installerPackageName != null) {
2072                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2073                            extras, 0 /*flags*/,
2074                            installerPackageName, null /*finishedReceiver*/,
2075                            updateUserIds, instantUserIds);
2076                }
2077
2078                // Send replaced for users that don't see the package for the first time
2079                if (update) {
2080                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2081                            packageName, extras, 0 /*flags*/,
2082                            null /*targetPackage*/, null /*finishedReceiver*/,
2083                            updateUserIds, instantUserIds);
2084                    if (installerPackageName != null) {
2085                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2086                                extras, 0 /*flags*/,
2087                                installerPackageName, null /*finishedReceiver*/,
2088                                updateUserIds, instantUserIds);
2089                    }
2090                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2091                            null /*package*/, null /*extras*/, 0 /*flags*/,
2092                            packageName /*targetPackage*/,
2093                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2094                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2095                    // First-install and we did a restore, so we're responsible for the
2096                    // first-launch broadcast.
2097                    if (DEBUG_BACKUP) {
2098                        Slog.i(TAG, "Post-restore of " + packageName
2099                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2100                    }
2101                    sendFirstLaunchBroadcast(packageName, installerPackage,
2102                            firstUserIds, firstInstantUserIds);
2103                }
2104
2105                // Send broadcast package appeared if forward locked/external for all users
2106                // treat asec-hosted packages like removable media on upgrade
2107                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2108                    if (DEBUG_INSTALL) {
2109                        Slog.i(TAG, "upgrading pkg " + res.pkg
2110                                + " is ASEC-hosted -> AVAILABLE");
2111                    }
2112                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2113                    ArrayList<String> pkgList = new ArrayList<>(1);
2114                    pkgList.add(packageName);
2115                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2116                }
2117            }
2118
2119            // Work that needs to happen on first install within each user
2120            if (firstUserIds != null && firstUserIds.length > 0) {
2121                synchronized (mPackages) {
2122                    for (int userId : firstUserIds) {
2123                        // If this app is a browser and it's newly-installed for some
2124                        // users, clear any default-browser state in those users. The
2125                        // app's nature doesn't depend on the user, so we can just check
2126                        // its browser nature in any user and generalize.
2127                        if (packageIsBrowser(packageName, userId)) {
2128                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2129                        }
2130
2131                        // We may also need to apply pending (restored) runtime
2132                        // permission grants within these users.
2133                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2134                    }
2135                }
2136            }
2137
2138            if (allNewUsers && !update) {
2139                notifyPackageAdded(packageName);
2140            }
2141
2142            // Log current value of "unknown sources" setting
2143            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2144                    getUnknownSourcesSettings());
2145
2146            // Remove the replaced package's older resources safely now
2147            // We delete after a gc for applications  on sdcard.
2148            if (res.removedInfo != null && res.removedInfo.args != null) {
2149                Runtime.getRuntime().gc();
2150                synchronized (mInstallLock) {
2151                    res.removedInfo.args.doPostDeleteLI(true);
2152                }
2153            } else {
2154                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2155                // and not block here.
2156                VMRuntime.getRuntime().requestConcurrentGC();
2157            }
2158
2159            // Notify DexManager that the package was installed for new users.
2160            // The updated users should already be indexed and the package code paths
2161            // should not change.
2162            // Don't notify the manager for ephemeral apps as they are not expected to
2163            // survive long enough to benefit of background optimizations.
2164            for (int userId : firstUserIds) {
2165                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2166                // There's a race currently where some install events may interleave with an uninstall.
2167                // This can lead to package info being null (b/36642664).
2168                if (info != null) {
2169                    mDexManager.notifyPackageInstalled(info, userId);
2170                }
2171            }
2172        }
2173
2174        // If someone is watching installs - notify them
2175        if (installObserver != null) {
2176            try {
2177                Bundle extras = extrasForInstallResult(res);
2178                installObserver.onPackageInstalled(res.name, res.returnCode,
2179                        res.returnMsg, extras);
2180            } catch (RemoteException e) {
2181                Slog.i(TAG, "Observer no longer exists.");
2182            }
2183        }
2184    }
2185
2186    private StorageEventListener mStorageListener = new StorageEventListener() {
2187        @Override
2188        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2189            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2190                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2191                    final String volumeUuid = vol.getFsUuid();
2192
2193                    // Clean up any users or apps that were removed or recreated
2194                    // while this volume was missing
2195                    sUserManager.reconcileUsers(volumeUuid);
2196                    reconcileApps(volumeUuid);
2197
2198                    // Clean up any install sessions that expired or were
2199                    // cancelled while this volume was missing
2200                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2201
2202                    loadPrivatePackages(vol);
2203
2204                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2205                    unloadPrivatePackages(vol);
2206                }
2207            }
2208        }
2209
2210        @Override
2211        public void onVolumeForgotten(String fsUuid) {
2212            if (TextUtils.isEmpty(fsUuid)) {
2213                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2214                return;
2215            }
2216
2217            // Remove any apps installed on the forgotten volume
2218            synchronized (mPackages) {
2219                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2220                for (PackageSetting ps : packages) {
2221                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2222                    deletePackageVersioned(new VersionedPackage(ps.name,
2223                            PackageManager.VERSION_CODE_HIGHEST),
2224                            new LegacyPackageDeleteObserver(null).getBinder(),
2225                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2226                    // Try very hard to release any references to this package
2227                    // so we don't risk the system server being killed due to
2228                    // open FDs
2229                    AttributeCache.instance().removePackage(ps.name);
2230                }
2231
2232                mSettings.onVolumeForgotten(fsUuid);
2233                mSettings.writeLPr();
2234            }
2235        }
2236    };
2237
2238    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2239        Bundle extras = null;
2240        switch (res.returnCode) {
2241            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2242                extras = new Bundle();
2243                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2244                        res.origPermission);
2245                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2246                        res.origPackage);
2247                break;
2248            }
2249            case PackageManager.INSTALL_SUCCEEDED: {
2250                extras = new Bundle();
2251                extras.putBoolean(Intent.EXTRA_REPLACING,
2252                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2253                break;
2254            }
2255        }
2256        return extras;
2257    }
2258
2259    void scheduleWriteSettingsLocked() {
2260        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2261            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2262        }
2263    }
2264
2265    void scheduleWritePackageListLocked(int userId) {
2266        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2267            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2268            msg.arg1 = userId;
2269            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2270        }
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2274        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2275        scheduleWritePackageRestrictionsLocked(userId);
2276    }
2277
2278    void scheduleWritePackageRestrictionsLocked(int userId) {
2279        final int[] userIds = (userId == UserHandle.USER_ALL)
2280                ? sUserManager.getUserIds() : new int[]{userId};
2281        for (int nextUserId : userIds) {
2282            if (!sUserManager.exists(nextUserId)) return;
2283            mDirtyUsers.add(nextUserId);
2284            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2285                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2286            }
2287        }
2288    }
2289
2290    public static PackageManagerService main(Context context, Installer installer,
2291            boolean factoryTest, boolean onlyCore) {
2292        // Self-check for initial settings.
2293        PackageManagerServiceCompilerMapping.checkProperties();
2294
2295        PackageManagerService m = new PackageManagerService(context, installer,
2296                factoryTest, onlyCore);
2297        m.enableSystemUserPackages();
2298        ServiceManager.addService("package", m);
2299        final PackageManagerNative pmn = m.new PackageManagerNative();
2300        ServiceManager.addService("package_native", pmn);
2301        return m;
2302    }
2303
2304    private void enableSystemUserPackages() {
2305        if (!UserManager.isSplitSystemUser()) {
2306            return;
2307        }
2308        // For system user, enable apps based on the following conditions:
2309        // - app is whitelisted or belong to one of these groups:
2310        //   -- system app which has no launcher icons
2311        //   -- system app which has INTERACT_ACROSS_USERS permission
2312        //   -- system IME app
2313        // - app is not in the blacklist
2314        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2315        Set<String> enableApps = new ArraySet<>();
2316        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2317                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2318                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2319        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2320        enableApps.addAll(wlApps);
2321        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2322                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2323        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2324        enableApps.removeAll(blApps);
2325        Log.i(TAG, "Applications installed for system user: " + enableApps);
2326        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2327                UserHandle.SYSTEM);
2328        final int allAppsSize = allAps.size();
2329        synchronized (mPackages) {
2330            for (int i = 0; i < allAppsSize; i++) {
2331                String pName = allAps.get(i);
2332                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2333                // Should not happen, but we shouldn't be failing if it does
2334                if (pkgSetting == null) {
2335                    continue;
2336                }
2337                boolean install = enableApps.contains(pName);
2338                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2339                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2340                            + " for system user");
2341                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2342                }
2343            }
2344            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2345        }
2346    }
2347
2348    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2349        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2350                Context.DISPLAY_SERVICE);
2351        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2352    }
2353
2354    /**
2355     * Requests that files preopted on a secondary system partition be copied to the data partition
2356     * if possible.  Note that the actual copying of the files is accomplished by init for security
2357     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2358     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2359     */
2360    private static void requestCopyPreoptedFiles() {
2361        final int WAIT_TIME_MS = 100;
2362        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2363        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2364            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2365            // We will wait for up to 100 seconds.
2366            final long timeStart = SystemClock.uptimeMillis();
2367            final long timeEnd = timeStart + 100 * 1000;
2368            long timeNow = timeStart;
2369            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2370                try {
2371                    Thread.sleep(WAIT_TIME_MS);
2372                } catch (InterruptedException e) {
2373                    // Do nothing
2374                }
2375                timeNow = SystemClock.uptimeMillis();
2376                if (timeNow > timeEnd) {
2377                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2378                    Slog.wtf(TAG, "cppreopt did not finish!");
2379                    break;
2380                }
2381            }
2382
2383            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2384        }
2385    }
2386
2387    public PackageManagerService(Context context, Installer installer,
2388            boolean factoryTest, boolean onlyCore) {
2389        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2390        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2391        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2392                SystemClock.uptimeMillis());
2393
2394        if (mSdkVersion <= 0) {
2395            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2396        }
2397
2398        mContext = context;
2399
2400        mFactoryTest = factoryTest;
2401        mOnlyCore = onlyCore;
2402        mMetrics = new DisplayMetrics();
2403        mInstaller = installer;
2404
2405        // Create sub-components that provide services / data. Order here is important.
2406        synchronized (mInstallLock) {
2407        synchronized (mPackages) {
2408            // Expose private service for system components to use.
2409            LocalServices.addService(
2410                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2411            sUserManager = new UserManagerService(context, this,
2412                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2413            mPermissionManager = PermissionManagerService.create(context,
2414                    new DefaultPermissionGrantedCallback() {
2415                        @Override
2416                        public void onDefaultRuntimePermissionsGranted(int userId) {
2417                            synchronized(mPackages) {
2418                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2419                            }
2420                        }
2421                    }, mPackages /*externalLock*/);
2422            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2423            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2424        }
2425        }
2426        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2427                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2429                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2430        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2431                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2439                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2440
2441        String separateProcesses = SystemProperties.get("debug.separate_processes");
2442        if (separateProcesses != null && separateProcesses.length() > 0) {
2443            if ("*".equals(separateProcesses)) {
2444                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2445                mSeparateProcesses = null;
2446                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2447            } else {
2448                mDefParseFlags = 0;
2449                mSeparateProcesses = separateProcesses.split(",");
2450                Slog.w(TAG, "Running with debug.separate_processes: "
2451                        + separateProcesses);
2452            }
2453        } else {
2454            mDefParseFlags = 0;
2455            mSeparateProcesses = null;
2456        }
2457
2458        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2459                "*dexopt*");
2460        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2461                installer, mInstallLock);
2462        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2463                dexManagerListener);
2464        mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock);
2465        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2466
2467        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2468                FgThread.get().getLooper());
2469
2470        getDefaultDisplayMetrics(context, mMetrics);
2471
2472        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2473        SystemConfig systemConfig = SystemConfig.getInstance();
2474        mAvailableFeatures = systemConfig.getAvailableFeatures();
2475        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2476
2477        mProtectedPackages = new ProtectedPackages(mContext);
2478
2479        synchronized (mInstallLock) {
2480        // writer
2481        synchronized (mPackages) {
2482            mHandlerThread = new ServiceThread(TAG,
2483                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2484            mHandlerThread.start();
2485            mHandler = new PackageHandler(mHandlerThread.getLooper());
2486            mProcessLoggingHandler = new ProcessLoggingHandler();
2487            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2488            mInstantAppRegistry = new InstantAppRegistry(this);
2489
2490            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2491            final int builtInLibCount = libConfig.size();
2492            for (int i = 0; i < builtInLibCount; i++) {
2493                String name = libConfig.keyAt(i);
2494                String path = libConfig.valueAt(i);
2495                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2496                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2497            }
2498
2499            SELinuxMMAC.readInstallPolicy();
2500
2501            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2502            FallbackCategoryProvider.loadFallbacks();
2503            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2504
2505            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2506            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2507            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2508
2509            // Clean up orphaned packages for which the code path doesn't exist
2510            // and they are an update to a system app - caused by bug/32321269
2511            final int packageSettingCount = mSettings.mPackages.size();
2512            for (int i = packageSettingCount - 1; i >= 0; i--) {
2513                PackageSetting ps = mSettings.mPackages.valueAt(i);
2514                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2515                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2516                    mSettings.mPackages.removeAt(i);
2517                    mSettings.enableSystemPackageLPw(ps.name);
2518                }
2519            }
2520
2521            if (mFirstBoot) {
2522                requestCopyPreoptedFiles();
2523            }
2524
2525            String customResolverActivity = Resources.getSystem().getString(
2526                    R.string.config_customResolverActivity);
2527            if (TextUtils.isEmpty(customResolverActivity)) {
2528                customResolverActivity = null;
2529            } else {
2530                mCustomResolverComponentName = ComponentName.unflattenFromString(
2531                        customResolverActivity);
2532            }
2533
2534            long startTime = SystemClock.uptimeMillis();
2535
2536            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2537                    startTime);
2538
2539            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2540            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2541
2542            if (bootClassPath == null) {
2543                Slog.w(TAG, "No BOOTCLASSPATH found!");
2544            }
2545
2546            if (systemServerClassPath == null) {
2547                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2548            }
2549
2550            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2551
2552            final VersionInfo ver = mSettings.getInternalVersion();
2553            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2554            if (mIsUpgrade) {
2555                logCriticalInfo(Log.INFO,
2556                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2557            }
2558
2559            // when upgrading from pre-M, promote system app permissions from install to runtime
2560            mPromoteSystemApps =
2561                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2562
2563            // When upgrading from pre-N, we need to handle package extraction like first boot,
2564            // as there is no profiling data available.
2565            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2566
2567            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2568
2569            // save off the names of pre-existing system packages prior to scanning; we don't
2570            // want to automatically grant runtime permissions for new system apps
2571            if (mPromoteSystemApps) {
2572                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2573                while (pkgSettingIter.hasNext()) {
2574                    PackageSetting ps = pkgSettingIter.next();
2575                    if (isSystemApp(ps)) {
2576                        mExistingSystemPackages.add(ps.name);
2577                    }
2578                }
2579            }
2580
2581            mCacheDir = preparePackageParserCache(mIsUpgrade);
2582
2583            // Set flag to monitor and not change apk file paths when
2584            // scanning install directories.
2585            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2586
2587            if (mIsUpgrade || mFirstBoot) {
2588                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2589            }
2590
2591            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2592            // For security and version matching reason, only consider
2593            // overlay packages if they reside in the right directory.
2594            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2595                    mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2597                    scanFlags
2598                    | SCAN_AS_SYSTEM
2599                    | SCAN_AS_VENDOR,
2600                    0);
2601            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2602                    mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2604                    scanFlags
2605                    | SCAN_AS_SYSTEM
2606                    | SCAN_AS_PRODUCT,
2607                    0);
2608
2609            mParallelPackageParserCallback.findStaticOverlayPackages();
2610
2611            // Find base frameworks (resource packages without code).
2612            scanDirTracedLI(frameworkDir,
2613                    mDefParseFlags
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2615                    scanFlags
2616                    | SCAN_NO_DEX
2617                    | SCAN_AS_SYSTEM
2618                    | SCAN_AS_PRIVILEGED,
2619                    0);
2620
2621            // Collect privileged system packages.
2622            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2623            scanDirTracedLI(privilegedAppDir,
2624                    mDefParseFlags
2625                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2626                    scanFlags
2627                    | SCAN_AS_SYSTEM
2628                    | SCAN_AS_PRIVILEGED,
2629                    0);
2630
2631            // Collect ordinary system packages.
2632            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2633            scanDirTracedLI(systemAppDir,
2634                    mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2636                    scanFlags
2637                    | SCAN_AS_SYSTEM,
2638                    0);
2639
2640            // Collect privileged vendor packages.
2641            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2642            try {
2643                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2644            } catch (IOException e) {
2645                // failed to look up canonical path, continue with original one
2646            }
2647            scanDirTracedLI(privilegedVendorAppDir,
2648                    mDefParseFlags
2649                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2650                    scanFlags
2651                    | SCAN_AS_SYSTEM
2652                    | SCAN_AS_VENDOR
2653                    | SCAN_AS_PRIVILEGED,
2654                    0);
2655
2656            // Collect ordinary vendor packages.
2657            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2658            try {
2659                vendorAppDir = vendorAppDir.getCanonicalFile();
2660            } catch (IOException e) {
2661                // failed to look up canonical path, continue with original one
2662            }
2663            scanDirTracedLI(vendorAppDir,
2664                    mDefParseFlags
2665                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2666                    scanFlags
2667                    | SCAN_AS_SYSTEM
2668                    | SCAN_AS_VENDOR,
2669                    0);
2670
2671            // Collect privileged odm packages. /odm is another vendor partition
2672            // other than /vendor.
2673            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2674                        "priv-app");
2675            try {
2676                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2677            } catch (IOException e) {
2678                // failed to look up canonical path, continue with original one
2679            }
2680            scanDirTracedLI(privilegedOdmAppDir,
2681                    mDefParseFlags
2682                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2683                    scanFlags
2684                    | SCAN_AS_SYSTEM
2685                    | SCAN_AS_VENDOR
2686                    | SCAN_AS_PRIVILEGED,
2687                    0);
2688
2689            // Collect ordinary odm packages. /odm is another vendor partition
2690            // other than /vendor.
2691            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2692            try {
2693                odmAppDir = odmAppDir.getCanonicalFile();
2694            } catch (IOException e) {
2695                // failed to look up canonical path, continue with original one
2696            }
2697            scanDirTracedLI(odmAppDir,
2698                    mDefParseFlags
2699                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2700                    scanFlags
2701                    | SCAN_AS_SYSTEM
2702                    | SCAN_AS_VENDOR,
2703                    0);
2704
2705            // Collect all OEM packages.
2706            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2707            scanDirTracedLI(oemAppDir,
2708                    mDefParseFlags
2709                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2710                    scanFlags
2711                    | SCAN_AS_SYSTEM
2712                    | SCAN_AS_OEM,
2713                    0);
2714
2715            // Collected privileged product packages.
2716            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2717            try {
2718                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2719            } catch (IOException e) {
2720                // failed to look up canonical path, continue with original one
2721            }
2722            scanDirTracedLI(privilegedProductAppDir,
2723                    mDefParseFlags
2724                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2725                    scanFlags
2726                    | SCAN_AS_SYSTEM
2727                    | SCAN_AS_PRODUCT
2728                    | SCAN_AS_PRIVILEGED,
2729                    0);
2730
2731            // Collect ordinary product packages.
2732            File productAppDir = new File(Environment.getProductDirectory(), "app");
2733            try {
2734                productAppDir = productAppDir.getCanonicalFile();
2735            } catch (IOException e) {
2736                // failed to look up canonical path, continue with original one
2737            }
2738            scanDirTracedLI(productAppDir,
2739                    mDefParseFlags
2740                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2741                    scanFlags
2742                    | SCAN_AS_SYSTEM
2743                    | SCAN_AS_PRODUCT,
2744                    0);
2745
2746            // Prune any system packages that no longer exist.
2747            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2748            // Stub packages must either be replaced with full versions in the /data
2749            // partition or be disabled.
2750            final List<String> stubSystemApps = new ArrayList<>();
2751            if (!mOnlyCore) {
2752                // do this first before mucking with mPackages for the "expecting better" case
2753                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2754                while (pkgIterator.hasNext()) {
2755                    final PackageParser.Package pkg = pkgIterator.next();
2756                    if (pkg.isStub) {
2757                        stubSystemApps.add(pkg.packageName);
2758                    }
2759                }
2760
2761                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2762                while (psit.hasNext()) {
2763                    PackageSetting ps = psit.next();
2764
2765                    /*
2766                     * If this is not a system app, it can't be a
2767                     * disable system app.
2768                     */
2769                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2770                        continue;
2771                    }
2772
2773                    /*
2774                     * If the package is scanned, it's not erased.
2775                     */
2776                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2777                    if (scannedPkg != null) {
2778                        /*
2779                         * If the system app is both scanned and in the
2780                         * disabled packages list, then it must have been
2781                         * added via OTA. Remove it from the currently
2782                         * scanned package so the previously user-installed
2783                         * application can be scanned.
2784                         */
2785                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2786                            logCriticalInfo(Log.WARN,
2787                                    "Expecting better updated system app for " + ps.name
2788                                    + "; removing system app.  Last known"
2789                                    + " codePath=" + ps.codePathString
2790                                    + ", versionCode=" + ps.versionCode
2791                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2792                            removePackageLI(scannedPkg, true);
2793                            mExpectingBetter.put(ps.name, ps.codePath);
2794                        }
2795
2796                        continue;
2797                    }
2798
2799                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2800                        psit.remove();
2801                        logCriticalInfo(Log.WARN, "System package " + ps.name
2802                                + " no longer exists; it's data will be wiped");
2803                        // Actual deletion of code and data will be handled by later
2804                        // reconciliation step
2805                    } else {
2806                        // we still have a disabled system package, but, it still might have
2807                        // been removed. check the code path still exists and check there's
2808                        // still a package. the latter can happen if an OTA keeps the same
2809                        // code path, but, changes the package name.
2810                        final PackageSetting disabledPs =
2811                                mSettings.getDisabledSystemPkgLPr(ps.name);
2812                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2813                                || disabledPs.pkg == null) {
2814                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2815                        }
2816                    }
2817                }
2818            }
2819
2820            //delete tmp files
2821            deleteTempPackageFiles();
2822
2823            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2824
2825            // Remove any shared userIDs that have no associated packages
2826            mSettings.pruneSharedUsersLPw();
2827            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2828            final int systemPackagesCount = mPackages.size();
2829            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2830                    + " ms, packageCount: " + systemPackagesCount
2831                    + " , timePerPackage: "
2832                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2833                    + " , cached: " + cachedSystemApps);
2834            if (mIsUpgrade && systemPackagesCount > 0) {
2835                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2836                        ((int) systemScanTime) / systemPackagesCount);
2837            }
2838            if (!mOnlyCore) {
2839                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2840                        SystemClock.uptimeMillis());
2841                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2842
2843                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2844                        | PackageParser.PARSE_FORWARD_LOCK,
2845                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2846
2847                // Remove disable package settings for updated system apps that were
2848                // removed via an OTA. If the update is no longer present, remove the
2849                // app completely. Otherwise, revoke their system privileges.
2850                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2851                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2852                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2853                    final String msg;
2854                    if (deletedPkg == null) {
2855                        // should have found an update, but, we didn't; remove everything
2856                        msg = "Updated system package " + deletedAppName
2857                                + " no longer exists; removing its data";
2858                        // Actual deletion of code and data will be handled by later
2859                        // reconciliation step
2860                    } else {
2861                        // found an update; revoke system privileges
2862                        msg = "Updated system package + " + deletedAppName
2863                                + " no longer exists; revoking system privileges";
2864
2865                        // Don't do anything if a stub is removed from the system image. If
2866                        // we were to remove the uncompressed version from the /data partition,
2867                        // this is where it'd be done.
2868
2869                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2870                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2871                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2872                    }
2873                    logCriticalInfo(Log.WARN, msg);
2874                }
2875
2876                /*
2877                 * Make sure all system apps that we expected to appear on
2878                 * the userdata partition actually showed up. If they never
2879                 * appeared, crawl back and revive the system version.
2880                 */
2881                for (int i = 0; i < mExpectingBetter.size(); i++) {
2882                    final String packageName = mExpectingBetter.keyAt(i);
2883                    if (!mPackages.containsKey(packageName)) {
2884                        final File scanFile = mExpectingBetter.valueAt(i);
2885
2886                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2887                                + " but never showed up; reverting to system");
2888
2889                        final @ParseFlags int reparseFlags;
2890                        final @ScanFlags int rescanFlags;
2891                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2892                            reparseFlags =
2893                                    mDefParseFlags |
2894                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2895                            rescanFlags =
2896                                    scanFlags
2897                                    | SCAN_AS_SYSTEM
2898                                    | SCAN_AS_PRIVILEGED;
2899                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2900                            reparseFlags =
2901                                    mDefParseFlags |
2902                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2903                            rescanFlags =
2904                                    scanFlags
2905                                    | SCAN_AS_SYSTEM;
2906                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2907                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2908                            reparseFlags =
2909                                    mDefParseFlags |
2910                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2911                            rescanFlags =
2912                                    scanFlags
2913                                    | SCAN_AS_SYSTEM
2914                                    | SCAN_AS_VENDOR
2915                                    | SCAN_AS_PRIVILEGED;
2916                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2917                                || FileUtils.contains(odmAppDir, scanFile)) {
2918                            reparseFlags =
2919                                    mDefParseFlags |
2920                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2921                            rescanFlags =
2922                                    scanFlags
2923                                    | SCAN_AS_SYSTEM
2924                                    | SCAN_AS_VENDOR;
2925                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2926                            reparseFlags =
2927                                    mDefParseFlags |
2928                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2929                            rescanFlags =
2930                                    scanFlags
2931                                    | SCAN_AS_SYSTEM
2932                                    | SCAN_AS_OEM;
2933                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2934                            reparseFlags =
2935                                    mDefParseFlags |
2936                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2937                            rescanFlags =
2938                                    scanFlags
2939                                    | SCAN_AS_SYSTEM
2940                                    | SCAN_AS_PRODUCT
2941                                    | SCAN_AS_PRIVILEGED;
2942                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2943                            reparseFlags =
2944                                    mDefParseFlags |
2945                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2946                            rescanFlags =
2947                                    scanFlags
2948                                    | SCAN_AS_SYSTEM
2949                                    | SCAN_AS_PRODUCT;
2950                        } else {
2951                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2952                            continue;
2953                        }
2954
2955                        mSettings.enableSystemPackageLPw(packageName);
2956
2957                        try {
2958                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2959                        } catch (PackageManagerException e) {
2960                            Slog.e(TAG, "Failed to parse original system package: "
2961                                    + e.getMessage());
2962                        }
2963                    }
2964                }
2965
2966                // Uncompress and install any stubbed system applications.
2967                // This must be done last to ensure all stubs are replaced or disabled.
2968                decompressSystemApplications(stubSystemApps, scanFlags);
2969
2970                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2971                                - cachedSystemApps;
2972
2973                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2974                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2975                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2976                        + " ms, packageCount: " + dataPackagesCount
2977                        + " , timePerPackage: "
2978                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2979                        + " , cached: " + cachedNonSystemApps);
2980                if (mIsUpgrade && dataPackagesCount > 0) {
2981                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2982                            ((int) dataScanTime) / dataPackagesCount);
2983                }
2984            }
2985            mExpectingBetter.clear();
2986
2987            // Resolve the storage manager.
2988            mStorageManagerPackage = getStorageManagerPackageName();
2989
2990            // Resolve protected action filters. Only the setup wizard is allowed to
2991            // have a high priority filter for these actions.
2992            mSetupWizardPackage = getSetupWizardPackageName();
2993            if (mProtectedFilters.size() > 0) {
2994                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2995                    Slog.i(TAG, "No setup wizard;"
2996                        + " All protected intents capped to priority 0");
2997                }
2998                for (ActivityIntentInfo filter : mProtectedFilters) {
2999                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
3000                        if (DEBUG_FILTERS) {
3001                            Slog.i(TAG, "Found setup wizard;"
3002                                + " allow priority " + filter.getPriority() + ";"
3003                                + " package: " + filter.activity.info.packageName
3004                                + " activity: " + filter.activity.className
3005                                + " priority: " + filter.getPriority());
3006                        }
3007                        // skip setup wizard; allow it to keep the high priority filter
3008                        continue;
3009                    }
3010                    if (DEBUG_FILTERS) {
3011                        Slog.i(TAG, "Protected action; cap priority to 0;"
3012                                + " package: " + filter.activity.info.packageName
3013                                + " activity: " + filter.activity.className
3014                                + " origPrio: " + filter.getPriority());
3015                    }
3016                    filter.setPriority(0);
3017                }
3018            }
3019
3020            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3021
3022            mDeferProtectedFilters = false;
3023            mProtectedFilters.clear();
3024
3025            // Now that we know all of the shared libraries, update all clients to have
3026            // the correct library paths.
3027            updateAllSharedLibrariesLPw(null);
3028
3029            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3030                // NOTE: We ignore potential failures here during a system scan (like
3031                // the rest of the commands above) because there's precious little we
3032                // can do about it. A settings error is reported, though.
3033                final List<String> changedAbiCodePath =
3034                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3035                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3036                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3037                        final String codePathString = changedAbiCodePath.get(i);
3038                        try {
3039                            mInstaller.rmdex(codePathString,
3040                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3041                        } catch (InstallerException ignored) {
3042                        }
3043                    }
3044                }
3045                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3046                // SELinux domain.
3047                setting.fixSeInfoLocked();
3048            }
3049
3050            // Now that we know all the packages we are keeping,
3051            // read and update their last usage times.
3052            mPackageUsage.read(mPackages);
3053            mCompilerStats.read();
3054
3055            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3056                    SystemClock.uptimeMillis());
3057            Slog.i(TAG, "Time to scan packages: "
3058                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3059                    + " seconds");
3060
3061            // If the platform SDK has changed since the last time we booted,
3062            // we need to re-grant app permission to catch any new ones that
3063            // appear.  This is really a hack, and means that apps can in some
3064            // cases get permissions that the user didn't initially explicitly
3065            // allow...  it would be nice to have some better way to handle
3066            // this situation.
3067            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3068            if (sdkUpdated) {
3069                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3070                        + mSdkVersion + "; regranting permissions for internal storage");
3071            }
3072            mPermissionManager.updateAllPermissions(
3073                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3074                    mPermissionCallback);
3075            ver.sdkVersion = mSdkVersion;
3076
3077            // If this is the first boot or an update from pre-M, and it is a normal
3078            // boot, then we need to initialize the default preferred apps across
3079            // all defined users.
3080            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3081                for (UserInfo user : sUserManager.getUsers(true)) {
3082                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3083                    applyFactoryDefaultBrowserLPw(user.id);
3084                    primeDomainVerificationsLPw(user.id);
3085                }
3086            }
3087
3088            // Prepare storage for system user really early during boot,
3089            // since core system apps like SettingsProvider and SystemUI
3090            // can't wait for user to start
3091            final int storageFlags;
3092            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3093                storageFlags = StorageManager.FLAG_STORAGE_DE;
3094            } else {
3095                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3096            }
3097            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3098                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3099                    true /* onlyCoreApps */);
3100            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3101                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3102                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3103                traceLog.traceBegin("AppDataFixup");
3104                try {
3105                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3106                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3107                } catch (InstallerException e) {
3108                    Slog.w(TAG, "Trouble fixing GIDs", e);
3109                }
3110                traceLog.traceEnd();
3111
3112                traceLog.traceBegin("AppDataPrepare");
3113                if (deferPackages == null || deferPackages.isEmpty()) {
3114                    return;
3115                }
3116                int count = 0;
3117                for (String pkgName : deferPackages) {
3118                    PackageParser.Package pkg = null;
3119                    synchronized (mPackages) {
3120                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3121                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3122                            pkg = ps.pkg;
3123                        }
3124                    }
3125                    if (pkg != null) {
3126                        synchronized (mInstallLock) {
3127                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3128                                    true /* maybeMigrateAppData */);
3129                        }
3130                        count++;
3131                    }
3132                }
3133                traceLog.traceEnd();
3134                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3135            }, "prepareAppData");
3136
3137            // If this is first boot after an OTA, and a normal boot, then
3138            // we need to clear code cache directories.
3139            // Note that we do *not* clear the application profiles. These remain valid
3140            // across OTAs and are used to drive profile verification (post OTA) and
3141            // profile compilation (without waiting to collect a fresh set of profiles).
3142            if (mIsUpgrade && !onlyCore) {
3143                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3144                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3145                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3146                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3147                        // No apps are running this early, so no need to freeze
3148                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3149                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3150                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3151                    }
3152                }
3153                ver.fingerprint = Build.FINGERPRINT;
3154            }
3155
3156            checkDefaultBrowser();
3157
3158            // clear only after permissions and other defaults have been updated
3159            mExistingSystemPackages.clear();
3160            mPromoteSystemApps = false;
3161
3162            // All the changes are done during package scanning.
3163            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3164
3165            // can downgrade to reader
3166            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3167            mSettings.writeLPr();
3168            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3169            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3170                    SystemClock.uptimeMillis());
3171
3172            if (!mOnlyCore) {
3173                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3174                mRequiredInstallerPackage = getRequiredInstallerLPr();
3175                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3176                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3177                if (mIntentFilterVerifierComponent != null) {
3178                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3179                            mIntentFilterVerifierComponent);
3180                } else {
3181                    mIntentFilterVerifier = null;
3182                }
3183                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3184                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3185                        SharedLibraryInfo.VERSION_UNDEFINED);
3186                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3187                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3188                        SharedLibraryInfo.VERSION_UNDEFINED);
3189            } else {
3190                mRequiredVerifierPackage = null;
3191                mRequiredInstallerPackage = null;
3192                mRequiredUninstallerPackage = null;
3193                mIntentFilterVerifierComponent = null;
3194                mIntentFilterVerifier = null;
3195                mServicesSystemSharedLibraryPackageName = null;
3196                mSharedSystemSharedLibraryPackageName = null;
3197            }
3198
3199            mInstallerService = new PackageInstallerService(context, this);
3200            final Pair<ComponentName, String> instantAppResolverComponent =
3201                    getInstantAppResolverLPr();
3202            if (instantAppResolverComponent != null) {
3203                if (DEBUG_INSTANT) {
3204                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3205                }
3206                mInstantAppResolverConnection = new InstantAppResolverConnection(
3207                        mContext, instantAppResolverComponent.first,
3208                        instantAppResolverComponent.second);
3209                mInstantAppResolverSettingsComponent =
3210                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3211            } else {
3212                mInstantAppResolverConnection = null;
3213                mInstantAppResolverSettingsComponent = null;
3214            }
3215            updateInstantAppInstallerLocked(null);
3216
3217            // Read and update the usage of dex files.
3218            // Do this at the end of PM init so that all the packages have their
3219            // data directory reconciled.
3220            // At this point we know the code paths of the packages, so we can validate
3221            // the disk file and build the internal cache.
3222            // The usage file is expected to be small so loading and verifying it
3223            // should take a fairly small time compare to the other activities (e.g. package
3224            // scanning).
3225            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3226            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3227            for (int userId : currentUserIds) {
3228                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3229            }
3230            mDexManager.load(userPackages);
3231            if (mIsUpgrade) {
3232                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3233                        (int) (SystemClock.uptimeMillis() - startTime));
3234            }
3235        } // synchronized (mPackages)
3236        } // synchronized (mInstallLock)
3237
3238        // Now after opening every single application zip, make sure they
3239        // are all flushed.  Not really needed, but keeps things nice and
3240        // tidy.
3241        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3242        Runtime.getRuntime().gc();
3243        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3244
3245        // The initial scanning above does many calls into installd while
3246        // holding the mPackages lock, but we're mostly interested in yelling
3247        // once we have a booted system.
3248        mInstaller.setWarnIfHeld(mPackages);
3249
3250        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3251    }
3252
3253    /**
3254     * Uncompress and install stub applications.
3255     * <p>In order to save space on the system partition, some applications are shipped in a
3256     * compressed form. In addition the compressed bits for the full application, the
3257     * system image contains a tiny stub comprised of only the Android manifest.
3258     * <p>During the first boot, attempt to uncompress and install the full application. If
3259     * the application can't be installed for any reason, disable the stub and prevent
3260     * uncompressing the full application during future boots.
3261     * <p>In order to forcefully attempt an installation of a full application, go to app
3262     * settings and enable the application.
3263     */
3264    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3265        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3266            final String pkgName = stubSystemApps.get(i);
3267            // skip if the system package is already disabled
3268            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3269                stubSystemApps.remove(i);
3270                continue;
3271            }
3272            // skip if the package isn't installed (?!); this should never happen
3273            final PackageParser.Package pkg = mPackages.get(pkgName);
3274            if (pkg == null) {
3275                stubSystemApps.remove(i);
3276                continue;
3277            }
3278            // skip if the package has been disabled by the user
3279            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3280            if (ps != null) {
3281                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3282                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3283                    stubSystemApps.remove(i);
3284                    continue;
3285                }
3286            }
3287
3288            if (DEBUG_COMPRESSION) {
3289                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3290            }
3291
3292            // uncompress the binary to its eventual destination on /data
3293            final File scanFile = decompressPackage(pkg);
3294            if (scanFile == null) {
3295                continue;
3296            }
3297
3298            // install the package to replace the stub on /system
3299            try {
3300                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3301                removePackageLI(pkg, true /*chatty*/);
3302                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3303                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3304                        UserHandle.USER_SYSTEM, "android");
3305                stubSystemApps.remove(i);
3306                continue;
3307            } catch (PackageManagerException e) {
3308                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3309            }
3310
3311            // any failed attempt to install the package will be cleaned up later
3312        }
3313
3314        // disable any stub still left; these failed to install the full application
3315        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3316            final String pkgName = stubSystemApps.get(i);
3317            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3318            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3319                    UserHandle.USER_SYSTEM, "android");
3320            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3321        }
3322    }
3323
3324    /**
3325     * Decompresses the given package on the system image onto
3326     * the /data partition.
3327     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3328     */
3329    private File decompressPackage(PackageParser.Package pkg) {
3330        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3331        if (compressedFiles == null || compressedFiles.length == 0) {
3332            if (DEBUG_COMPRESSION) {
3333                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3334            }
3335            return null;
3336        }
3337        final File dstCodePath =
3338                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3339        int ret = PackageManager.INSTALL_SUCCEEDED;
3340        try {
3341            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3342            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3343            for (File srcFile : compressedFiles) {
3344                final String srcFileName = srcFile.getName();
3345                final String dstFileName = srcFileName.substring(
3346                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3347                final File dstFile = new File(dstCodePath, dstFileName);
3348                ret = decompressFile(srcFile, dstFile);
3349                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3350                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3351                            + "; pkg: " + pkg.packageName
3352                            + ", file: " + dstFileName);
3353                    break;
3354                }
3355            }
3356        } catch (ErrnoException e) {
3357            logCriticalInfo(Log.ERROR, "Failed to decompress"
3358                    + "; pkg: " + pkg.packageName
3359                    + ", err: " + e.errno);
3360        }
3361        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3362            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3363            NativeLibraryHelper.Handle handle = null;
3364            try {
3365                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3366                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3367                        null /*abiOverride*/);
3368            } catch (IOException e) {
3369                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3370                        + "; pkg: " + pkg.packageName);
3371                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3372            } finally {
3373                IoUtils.closeQuietly(handle);
3374            }
3375        }
3376        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3377            if (dstCodePath == null || !dstCodePath.exists()) {
3378                return null;
3379            }
3380            removeCodePathLI(dstCodePath);
3381            return null;
3382        }
3383
3384        return dstCodePath;
3385    }
3386
3387    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3388        // we're only interested in updating the installer appliction when 1) it's not
3389        // already set or 2) the modified package is the installer
3390        if (mInstantAppInstallerActivity != null
3391                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3392                        .equals(modifiedPackage)) {
3393            return;
3394        }
3395        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3396    }
3397
3398    private static File preparePackageParserCache(boolean isUpgrade) {
3399        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3400            return null;
3401        }
3402
3403        // Disable package parsing on eng builds to allow for faster incremental development.
3404        if (Build.IS_ENG) {
3405            return null;
3406        }
3407
3408        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3409            Slog.i(TAG, "Disabling package parser cache due to system property.");
3410            return null;
3411        }
3412
3413        // The base directory for the package parser cache lives under /data/system/.
3414        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3415                "package_cache");
3416        if (cacheBaseDir == null) {
3417            return null;
3418        }
3419
3420        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3421        // This also serves to "GC" unused entries when the package cache version changes (which
3422        // can only happen during upgrades).
3423        if (isUpgrade) {
3424            FileUtils.deleteContents(cacheBaseDir);
3425        }
3426
3427
3428        // Return the versioned package cache directory. This is something like
3429        // "/data/system/package_cache/1"
3430        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3431
3432        if (cacheDir == null) {
3433            // Something went wrong. Attempt to delete everything and return.
3434            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3435            FileUtils.deleteContentsAndDir(cacheBaseDir);
3436            return null;
3437        }
3438
3439        // The following is a workaround to aid development on non-numbered userdebug
3440        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3441        // the system partition is newer.
3442        //
3443        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3444        // that starts with "eng." to signify that this is an engineering build and not
3445        // destined for release.
3446        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3447            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3448
3449            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3450            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3451            // in general and should not be used for production changes. In this specific case,
3452            // we know that they will work.
3453            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3454            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3455                FileUtils.deleteContents(cacheBaseDir);
3456                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3457            }
3458        }
3459
3460        return cacheDir;
3461    }
3462
3463    @Override
3464    public boolean isFirstBoot() {
3465        // allow instant applications
3466        return mFirstBoot;
3467    }
3468
3469    @Override
3470    public boolean isOnlyCoreApps() {
3471        // allow instant applications
3472        return mOnlyCore;
3473    }
3474
3475    @Override
3476    public boolean isUpgrade() {
3477        // allow instant applications
3478        // The system property allows testing ota flow when upgraded to the same image.
3479        return mIsUpgrade || SystemProperties.getBoolean(
3480                "persist.pm.mock-upgrade", false /* default */);
3481    }
3482
3483    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3484        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3485
3486        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3487                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3488                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3489        if (matches.size() == 1) {
3490            return matches.get(0).getComponentInfo().packageName;
3491        } else if (matches.size() == 0) {
3492            Log.e(TAG, "There should probably be a verifier, but, none were found");
3493            return null;
3494        }
3495        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3496    }
3497
3498    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3499        synchronized (mPackages) {
3500            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3501            if (libraryEntry == null) {
3502                throw new IllegalStateException("Missing required shared library:" + name);
3503            }
3504            return libraryEntry.apk;
3505        }
3506    }
3507
3508    private @NonNull String getRequiredInstallerLPr() {
3509        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3510        intent.addCategory(Intent.CATEGORY_DEFAULT);
3511        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3512
3513        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3514                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3515                UserHandle.USER_SYSTEM);
3516        if (matches.size() == 1) {
3517            ResolveInfo resolveInfo = matches.get(0);
3518            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3519                throw new RuntimeException("The installer must be a privileged app");
3520            }
3521            return matches.get(0).getComponentInfo().packageName;
3522        } else {
3523            throw new RuntimeException("There must be exactly one installer; found " + matches);
3524        }
3525    }
3526
3527    private @NonNull String getRequiredUninstallerLPr() {
3528        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3529        intent.addCategory(Intent.CATEGORY_DEFAULT);
3530        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3531
3532        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3533                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3534                UserHandle.USER_SYSTEM);
3535        if (resolveInfo == null ||
3536                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3537            throw new RuntimeException("There must be exactly one uninstaller; found "
3538                    + resolveInfo);
3539        }
3540        return resolveInfo.getComponentInfo().packageName;
3541    }
3542
3543    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3544        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3545
3546        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3547                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3548                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3549        ResolveInfo best = null;
3550        final int N = matches.size();
3551        for (int i = 0; i < N; i++) {
3552            final ResolveInfo cur = matches.get(i);
3553            final String packageName = cur.getComponentInfo().packageName;
3554            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3555                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3556                continue;
3557            }
3558
3559            if (best == null || cur.priority > best.priority) {
3560                best = cur;
3561            }
3562        }
3563
3564        if (best != null) {
3565            return best.getComponentInfo().getComponentName();
3566        }
3567        Slog.w(TAG, "Intent filter verifier not found");
3568        return null;
3569    }
3570
3571    @Override
3572    public @Nullable ComponentName getInstantAppResolverComponent() {
3573        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3574            return null;
3575        }
3576        synchronized (mPackages) {
3577            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3578            if (instantAppResolver == null) {
3579                return null;
3580            }
3581            return instantAppResolver.first;
3582        }
3583    }
3584
3585    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3586        final String[] packageArray =
3587                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3588        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3589            if (DEBUG_INSTANT) {
3590                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3591            }
3592            return null;
3593        }
3594
3595        final int callingUid = Binder.getCallingUid();
3596        final int resolveFlags =
3597                MATCH_DIRECT_BOOT_AWARE
3598                | MATCH_DIRECT_BOOT_UNAWARE
3599                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3600        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3601        final Intent resolverIntent = new Intent(actionName);
3602        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3603                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3604        final int N = resolvers.size();
3605        if (N == 0) {
3606            if (DEBUG_INSTANT) {
3607                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3608            }
3609            return null;
3610        }
3611
3612        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3613        for (int i = 0; i < N; i++) {
3614            final ResolveInfo info = resolvers.get(i);
3615
3616            if (info.serviceInfo == null) {
3617                continue;
3618            }
3619
3620            final String packageName = info.serviceInfo.packageName;
3621            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3622                if (DEBUG_INSTANT) {
3623                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3624                            + " pkg: " + packageName + ", info:" + info);
3625                }
3626                continue;
3627            }
3628
3629            if (DEBUG_INSTANT) {
3630                Slog.v(TAG, "Ephemeral resolver found;"
3631                        + " pkg: " + packageName + ", info:" + info);
3632            }
3633            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3634        }
3635        if (DEBUG_INSTANT) {
3636            Slog.v(TAG, "Ephemeral resolver NOT found");
3637        }
3638        return null;
3639    }
3640
3641    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3642        String[] orderedActions = Build.IS_ENG
3643                ? new String[]{
3644                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3645                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3646                : new String[]{
3647                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3648
3649        final int resolveFlags =
3650                MATCH_DIRECT_BOOT_AWARE
3651                        | MATCH_DIRECT_BOOT_UNAWARE
3652                        | Intent.FLAG_IGNORE_EPHEMERAL
3653                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3654        final Intent intent = new Intent();
3655        intent.addCategory(Intent.CATEGORY_DEFAULT);
3656        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3657        List<ResolveInfo> matches = null;
3658        for (String action : orderedActions) {
3659            intent.setAction(action);
3660            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3661                    resolveFlags, UserHandle.USER_SYSTEM);
3662            if (matches.isEmpty()) {
3663                if (DEBUG_INSTANT) {
3664                    Slog.d(TAG, "Instant App installer not found with " + action);
3665                }
3666            } else {
3667                break;
3668            }
3669        }
3670        Iterator<ResolveInfo> iter = matches.iterator();
3671        while (iter.hasNext()) {
3672            final ResolveInfo rInfo = iter.next();
3673            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3674            if (ps != null) {
3675                final PermissionsState permissionsState = ps.getPermissionsState();
3676                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3677                        || Build.IS_ENG) {
3678                    continue;
3679                }
3680            }
3681            iter.remove();
3682        }
3683        if (matches.size() == 0) {
3684            return null;
3685        } else if (matches.size() == 1) {
3686            return (ActivityInfo) matches.get(0).getComponentInfo();
3687        } else {
3688            throw new RuntimeException(
3689                    "There must be at most one ephemeral installer; found " + matches);
3690        }
3691    }
3692
3693    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3694            @NonNull ComponentName resolver) {
3695        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3696                .addCategory(Intent.CATEGORY_DEFAULT)
3697                .setPackage(resolver.getPackageName());
3698        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3699        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3700                UserHandle.USER_SYSTEM);
3701        if (matches.isEmpty()) {
3702            return null;
3703        }
3704        return matches.get(0).getComponentInfo().getComponentName();
3705    }
3706
3707    private void primeDomainVerificationsLPw(int userId) {
3708        if (DEBUG_DOMAIN_VERIFICATION) {
3709            Slog.d(TAG, "Priming domain verifications in user " + userId);
3710        }
3711
3712        SystemConfig systemConfig = SystemConfig.getInstance();
3713        ArraySet<String> packages = systemConfig.getLinkedApps();
3714
3715        for (String packageName : packages) {
3716            PackageParser.Package pkg = mPackages.get(packageName);
3717            if (pkg != null) {
3718                if (!pkg.isSystem()) {
3719                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3720                    continue;
3721                }
3722
3723                ArraySet<String> domains = null;
3724                for (PackageParser.Activity a : pkg.activities) {
3725                    for (ActivityIntentInfo filter : a.intents) {
3726                        if (hasValidDomains(filter)) {
3727                            if (domains == null) {
3728                                domains = new ArraySet<String>();
3729                            }
3730                            domains.addAll(filter.getHostsList());
3731                        }
3732                    }
3733                }
3734
3735                if (domains != null && domains.size() > 0) {
3736                    if (DEBUG_DOMAIN_VERIFICATION) {
3737                        Slog.v(TAG, "      + " + packageName);
3738                    }
3739                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3740                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3741                    // and then 'always' in the per-user state actually used for intent resolution.
3742                    final IntentFilterVerificationInfo ivi;
3743                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3744                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3745                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3746                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3747                } else {
3748                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3749                            + "' does not handle web links");
3750                }
3751            } else {
3752                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3753            }
3754        }
3755
3756        scheduleWritePackageRestrictionsLocked(userId);
3757        scheduleWriteSettingsLocked();
3758    }
3759
3760    private void applyFactoryDefaultBrowserLPw(int userId) {
3761        // The default browser app's package name is stored in a string resource,
3762        // with a product-specific overlay used for vendor customization.
3763        String browserPkg = mContext.getResources().getString(
3764                com.android.internal.R.string.default_browser);
3765        if (!TextUtils.isEmpty(browserPkg)) {
3766            // non-empty string => required to be a known package
3767            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3768            if (ps == null) {
3769                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3770                browserPkg = null;
3771            } else {
3772                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3773            }
3774        }
3775
3776        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3777        // default.  If there's more than one, just leave everything alone.
3778        if (browserPkg == null) {
3779            calculateDefaultBrowserLPw(userId);
3780        }
3781    }
3782
3783    private void calculateDefaultBrowserLPw(int userId) {
3784        List<String> allBrowsers = resolveAllBrowserApps(userId);
3785        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3786        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3787    }
3788
3789    private List<String> resolveAllBrowserApps(int userId) {
3790        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3791        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3792                PackageManager.MATCH_ALL, userId);
3793
3794        final int count = list.size();
3795        List<String> result = new ArrayList<String>(count);
3796        for (int i=0; i<count; i++) {
3797            ResolveInfo info = list.get(i);
3798            if (info.activityInfo == null
3799                    || !info.handleAllWebDataURI
3800                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3801                    || result.contains(info.activityInfo.packageName)) {
3802                continue;
3803            }
3804            result.add(info.activityInfo.packageName);
3805        }
3806
3807        return result;
3808    }
3809
3810    private boolean packageIsBrowser(String packageName, int userId) {
3811        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3812                PackageManager.MATCH_ALL, userId);
3813        final int N = list.size();
3814        for (int i = 0; i < N; i++) {
3815            ResolveInfo info = list.get(i);
3816            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3817                return true;
3818            }
3819        }
3820        return false;
3821    }
3822
3823    private void checkDefaultBrowser() {
3824        final int myUserId = UserHandle.myUserId();
3825        final String packageName = getDefaultBrowserPackageName(myUserId);
3826        if (packageName != null) {
3827            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3828            if (info == null) {
3829                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3830                synchronized (mPackages) {
3831                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3832                }
3833            }
3834        }
3835    }
3836
3837    @Override
3838    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3839            throws RemoteException {
3840        try {
3841            return super.onTransact(code, data, reply, flags);
3842        } catch (RuntimeException e) {
3843            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3844                Slog.wtf(TAG, "Package Manager Crash", e);
3845            }
3846            throw e;
3847        }
3848    }
3849
3850    static int[] appendInts(int[] cur, int[] add) {
3851        if (add == null) return cur;
3852        if (cur == null) return add;
3853        final int N = add.length;
3854        for (int i=0; i<N; i++) {
3855            cur = appendInt(cur, add[i]);
3856        }
3857        return cur;
3858    }
3859
3860    /**
3861     * Returns whether or not a full application can see an instant application.
3862     * <p>
3863     * Currently, there are three cases in which this can occur:
3864     * <ol>
3865     * <li>The calling application is a "special" process. Special processes
3866     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3867     * <li>The calling application has the permission
3868     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3869     * <li>The calling application is the default launcher on the
3870     *     system partition.</li>
3871     * </ol>
3872     */
3873    private boolean canViewInstantApps(int callingUid, int userId) {
3874        if (callingUid < Process.FIRST_APPLICATION_UID) {
3875            return true;
3876        }
3877        if (mContext.checkCallingOrSelfPermission(
3878                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3879            return true;
3880        }
3881        if (mContext.checkCallingOrSelfPermission(
3882                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3883            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3884            if (homeComponent != null
3885                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3886                return true;
3887            }
3888        }
3889        return false;
3890    }
3891
3892    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3893        if (!sUserManager.exists(userId)) return null;
3894        if (ps == null) {
3895            return null;
3896        }
3897        final int callingUid = Binder.getCallingUid();
3898        // Filter out ephemeral app metadata:
3899        //   * The system/shell/root can see metadata for any app
3900        //   * An installed app can see metadata for 1) other installed apps
3901        //     and 2) ephemeral apps that have explicitly interacted with it
3902        //   * Ephemeral apps can only see their own data and exposed installed apps
3903        //   * Holding a signature permission allows seeing instant apps
3904        if (filterAppAccessLPr(ps, callingUid, userId)) {
3905            return null;
3906        }
3907
3908        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3909                && ps.isSystem()) {
3910            flags |= MATCH_ANY_USER;
3911        }
3912
3913        final PackageUserState state = ps.readUserState(userId);
3914        PackageParser.Package p = ps.pkg;
3915        if (p != null) {
3916            final PermissionsState permissionsState = ps.getPermissionsState();
3917
3918            // Compute GIDs only if requested
3919            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3920                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3921            // Compute granted permissions only if package has requested permissions
3922            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3923                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3924
3925            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3926                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3927
3928            if (packageInfo == null) {
3929                return null;
3930            }
3931
3932            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3933                    resolveExternalPackageNameLPr(p);
3934
3935            return packageInfo;
3936        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3937            PackageInfo pi = new PackageInfo();
3938            pi.packageName = ps.name;
3939            pi.setLongVersionCode(ps.versionCode);
3940            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3941            pi.firstInstallTime = ps.firstInstallTime;
3942            pi.lastUpdateTime = ps.lastUpdateTime;
3943
3944            ApplicationInfo ai = new ApplicationInfo();
3945            ai.packageName = ps.name;
3946            ai.uid = UserHandle.getUid(userId, ps.appId);
3947            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3948            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3949            ai.setVersionCode(ps.versionCode);
3950            ai.flags = ps.pkgFlags;
3951            ai.privateFlags = ps.pkgPrivateFlags;
3952            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3953
3954            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3955                    + ps.name + "]. Provides a minimum info.");
3956            return pi;
3957        } else {
3958            return null;
3959        }
3960    }
3961
3962    @Override
3963    public void checkPackageStartable(String packageName, int userId) {
3964        final int callingUid = Binder.getCallingUid();
3965        if (getInstantAppPackageName(callingUid) != null) {
3966            throw new SecurityException("Instant applications don't have access to this method");
3967        }
3968        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3969        synchronized (mPackages) {
3970            final PackageSetting ps = mSettings.mPackages.get(packageName);
3971            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3972                throw new SecurityException("Package " + packageName + " was not found!");
3973            }
3974
3975            if (!ps.getInstalled(userId)) {
3976                throw new SecurityException(
3977                        "Package " + packageName + " was not installed for user " + userId + "!");
3978            }
3979
3980            if (mSafeMode && !ps.isSystem()) {
3981                throw new SecurityException("Package " + packageName + " not a system app!");
3982            }
3983
3984            if (mFrozenPackages.contains(packageName)) {
3985                throw new SecurityException("Package " + packageName + " is currently frozen!");
3986            }
3987
3988            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3989                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3990            }
3991        }
3992    }
3993
3994    @Override
3995    public boolean isPackageAvailable(String packageName, int userId) {
3996        if (!sUserManager.exists(userId)) return false;
3997        final int callingUid = Binder.getCallingUid();
3998        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3999                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4000        synchronized (mPackages) {
4001            PackageParser.Package p = mPackages.get(packageName);
4002            if (p != null) {
4003                final PackageSetting ps = (PackageSetting) p.mExtras;
4004                if (filterAppAccessLPr(ps, callingUid, userId)) {
4005                    return false;
4006                }
4007                if (ps != null) {
4008                    final PackageUserState state = ps.readUserState(userId);
4009                    if (state != null) {
4010                        return PackageParser.isAvailable(state);
4011                    }
4012                }
4013            }
4014        }
4015        return false;
4016    }
4017
4018    @Override
4019    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4020        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4021                flags, Binder.getCallingUid(), userId);
4022    }
4023
4024    @Override
4025    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4026            int flags, int userId) {
4027        return getPackageInfoInternal(versionedPackage.getPackageName(),
4028                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4029    }
4030
4031    /**
4032     * Important: The provided filterCallingUid is used exclusively to filter out packages
4033     * that can be seen based on user state. It's typically the original caller uid prior
4034     * to clearing. Because it can only be provided by trusted code, it's value can be
4035     * trusted and will be used as-is; unlike userId which will be validated by this method.
4036     */
4037    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4038            int flags, int filterCallingUid, int userId) {
4039        if (!sUserManager.exists(userId)) return null;
4040        flags = updateFlagsForPackage(flags, userId, packageName);
4041        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4042                false /* requireFullPermission */, false /* checkShell */, "get package info");
4043
4044        // reader
4045        synchronized (mPackages) {
4046            // Normalize package name to handle renamed packages and static libs
4047            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4048
4049            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4050            if (matchFactoryOnly) {
4051                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4052                if (ps != null) {
4053                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4054                        return null;
4055                    }
4056                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4057                        return null;
4058                    }
4059                    return generatePackageInfo(ps, flags, userId);
4060                }
4061            }
4062
4063            PackageParser.Package p = mPackages.get(packageName);
4064            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4065                return null;
4066            }
4067            if (DEBUG_PACKAGE_INFO)
4068                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4069            if (p != null) {
4070                final PackageSetting ps = (PackageSetting) p.mExtras;
4071                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4072                    return null;
4073                }
4074                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4075                    return null;
4076                }
4077                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4078            }
4079            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4080                final PackageSetting ps = mSettings.mPackages.get(packageName);
4081                if (ps == null) return null;
4082                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4083                    return null;
4084                }
4085                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4086                    return null;
4087                }
4088                return generatePackageInfo(ps, flags, userId);
4089            }
4090        }
4091        return null;
4092    }
4093
4094    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4095        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4096            return true;
4097        }
4098        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4099            return true;
4100        }
4101        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4102            return true;
4103        }
4104        return false;
4105    }
4106
4107    private boolean isComponentVisibleToInstantApp(
4108            @Nullable ComponentName component, @ComponentType int type) {
4109        if (type == TYPE_ACTIVITY) {
4110            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4111            if (activity == null) {
4112                return false;
4113            }
4114            final boolean visibleToInstantApp =
4115                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4116            final boolean explicitlyVisibleToInstantApp =
4117                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4118            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4119        } else if (type == TYPE_RECEIVER) {
4120            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4121            if (activity == null) {
4122                return false;
4123            }
4124            final boolean visibleToInstantApp =
4125                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4126            final boolean explicitlyVisibleToInstantApp =
4127                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4128            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4129        } else if (type == TYPE_SERVICE) {
4130            final PackageParser.Service service = mServices.mServices.get(component);
4131            return service != null
4132                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4133                    : false;
4134        } else if (type == TYPE_PROVIDER) {
4135            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4136            return provider != null
4137                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4138                    : false;
4139        } else if (type == TYPE_UNKNOWN) {
4140            return isComponentVisibleToInstantApp(component);
4141        }
4142        return false;
4143    }
4144
4145    /**
4146     * Returns whether or not access to the application should be filtered.
4147     * <p>
4148     * Access may be limited based upon whether the calling or target applications
4149     * are instant applications.
4150     *
4151     * @see #canAccessInstantApps(int)
4152     */
4153    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4154            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4155        // if we're in an isolated process, get the real calling UID
4156        if (Process.isIsolated(callingUid)) {
4157            callingUid = mIsolatedOwners.get(callingUid);
4158        }
4159        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4160        final boolean callerIsInstantApp = instantAppPkgName != null;
4161        if (ps == null) {
4162            if (callerIsInstantApp) {
4163                // pretend the application exists, but, needs to be filtered
4164                return true;
4165            }
4166            return false;
4167        }
4168        // if the target and caller are the same application, don't filter
4169        if (isCallerSameApp(ps.name, callingUid)) {
4170            return false;
4171        }
4172        if (callerIsInstantApp) {
4173            // both caller and target are both instant, but, different applications, filter
4174            if (ps.getInstantApp(userId)) {
4175                return true;
4176            }
4177            // request for a specific component; if it hasn't been explicitly exposed through
4178            // property or instrumentation target, filter
4179            if (component != null) {
4180                final PackageParser.Instrumentation instrumentation =
4181                        mInstrumentation.get(component);
4182                if (instrumentation != null
4183                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4184                    return false;
4185                }
4186                return !isComponentVisibleToInstantApp(component, componentType);
4187            }
4188            // request for application; if no components have been explicitly exposed, filter
4189            return !ps.pkg.visibleToInstantApps;
4190        }
4191        if (ps.getInstantApp(userId)) {
4192            // caller can see all components of all instant applications, don't filter
4193            if (canViewInstantApps(callingUid, userId)) {
4194                return false;
4195            }
4196            // request for a specific instant application component, filter
4197            if (component != null) {
4198                return true;
4199            }
4200            // request for an instant application; if the caller hasn't been granted access, filter
4201            return !mInstantAppRegistry.isInstantAccessGranted(
4202                    userId, UserHandle.getAppId(callingUid), ps.appId);
4203        }
4204        return false;
4205    }
4206
4207    /**
4208     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4209     */
4210    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4211        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4212    }
4213
4214    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4215            int flags) {
4216        // Callers can access only the libs they depend on, otherwise they need to explicitly
4217        // ask for the shared libraries given the caller is allowed to access all static libs.
4218        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4219            // System/shell/root get to see all static libs
4220            final int appId = UserHandle.getAppId(uid);
4221            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4222                    || appId == Process.ROOT_UID) {
4223                return false;
4224            }
4225            // Installer gets to see all static libs.
4226            if (PackageManager.PERMISSION_GRANTED
4227                    == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
4228                return false;
4229            }
4230        }
4231
4232        // No package means no static lib as it is always on internal storage
4233        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4234            return false;
4235        }
4236
4237        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4238                ps.pkg.staticSharedLibVersion);
4239        if (libEntry == null) {
4240            return false;
4241        }
4242
4243        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4244        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4245        if (uidPackageNames == null) {
4246            return true;
4247        }
4248
4249        for (String uidPackageName : uidPackageNames) {
4250            if (ps.name.equals(uidPackageName)) {
4251                return false;
4252            }
4253            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4254            if (uidPs != null) {
4255                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4256                        libEntry.info.getName());
4257                if (index < 0) {
4258                    continue;
4259                }
4260                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4261                    return false;
4262                }
4263            }
4264        }
4265        return true;
4266    }
4267
4268    @Override
4269    public String[] currentToCanonicalPackageNames(String[] names) {
4270        final int callingUid = Binder.getCallingUid();
4271        if (getInstantAppPackageName(callingUid) != null) {
4272            return names;
4273        }
4274        final String[] out = new String[names.length];
4275        // reader
4276        synchronized (mPackages) {
4277            final int callingUserId = UserHandle.getUserId(callingUid);
4278            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4279            for (int i=names.length-1; i>=0; i--) {
4280                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4281                boolean translateName = false;
4282                if (ps != null && ps.realName != null) {
4283                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4284                    translateName = !targetIsInstantApp
4285                            || canViewInstantApps
4286                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4287                                    UserHandle.getAppId(callingUid), ps.appId);
4288                }
4289                out[i] = translateName ? ps.realName : names[i];
4290            }
4291        }
4292        return out;
4293    }
4294
4295    @Override
4296    public String[] canonicalToCurrentPackageNames(String[] names) {
4297        final int callingUid = Binder.getCallingUid();
4298        if (getInstantAppPackageName(callingUid) != null) {
4299            return names;
4300        }
4301        final String[] out = new String[names.length];
4302        // reader
4303        synchronized (mPackages) {
4304            final int callingUserId = UserHandle.getUserId(callingUid);
4305            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4306            for (int i=names.length-1; i>=0; i--) {
4307                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4308                boolean translateName = false;
4309                if (cur != null) {
4310                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4311                    final boolean targetIsInstantApp =
4312                            ps != null && ps.getInstantApp(callingUserId);
4313                    translateName = !targetIsInstantApp
4314                            || canViewInstantApps
4315                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4316                                    UserHandle.getAppId(callingUid), ps.appId);
4317                }
4318                out[i] = translateName ? cur : names[i];
4319            }
4320        }
4321        return out;
4322    }
4323
4324    @Override
4325    public int getPackageUid(String packageName, int flags, int userId) {
4326        if (!sUserManager.exists(userId)) return -1;
4327        final int callingUid = Binder.getCallingUid();
4328        flags = updateFlagsForPackage(flags, userId, packageName);
4329        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4330                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4331
4332        // reader
4333        synchronized (mPackages) {
4334            final PackageParser.Package p = mPackages.get(packageName);
4335            if (p != null && p.isMatch(flags)) {
4336                PackageSetting ps = (PackageSetting) p.mExtras;
4337                if (filterAppAccessLPr(ps, callingUid, userId)) {
4338                    return -1;
4339                }
4340                return UserHandle.getUid(userId, p.applicationInfo.uid);
4341            }
4342            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4343                final PackageSetting ps = mSettings.mPackages.get(packageName);
4344                if (ps != null && ps.isMatch(flags)
4345                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4346                    return UserHandle.getUid(userId, ps.appId);
4347                }
4348            }
4349        }
4350
4351        return -1;
4352    }
4353
4354    @Override
4355    public int[] getPackageGids(String packageName, int flags, int userId) {
4356        if (!sUserManager.exists(userId)) return null;
4357        final int callingUid = Binder.getCallingUid();
4358        flags = updateFlagsForPackage(flags, userId, packageName);
4359        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4360                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4361
4362        // reader
4363        synchronized (mPackages) {
4364            final PackageParser.Package p = mPackages.get(packageName);
4365            if (p != null && p.isMatch(flags)) {
4366                PackageSetting ps = (PackageSetting) p.mExtras;
4367                if (filterAppAccessLPr(ps, callingUid, userId)) {
4368                    return null;
4369                }
4370                // TODO: Shouldn't this be checking for package installed state for userId and
4371                // return null?
4372                return ps.getPermissionsState().computeGids(userId);
4373            }
4374            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4375                final PackageSetting ps = mSettings.mPackages.get(packageName);
4376                if (ps != null && ps.isMatch(flags)
4377                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4378                    return ps.getPermissionsState().computeGids(userId);
4379                }
4380            }
4381        }
4382
4383        return null;
4384    }
4385
4386    @Override
4387    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4388        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4389    }
4390
4391    @Override
4392    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4393            int flags) {
4394        final List<PermissionInfo> permissionList =
4395                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4396        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4397    }
4398
4399    @Override
4400    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4401        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4402    }
4403
4404    @Override
4405    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4406        final List<PermissionGroupInfo> permissionList =
4407                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4408        return (permissionList == null)
4409                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4410    }
4411
4412    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4413            int filterCallingUid, int userId) {
4414        if (!sUserManager.exists(userId)) return null;
4415        PackageSetting ps = mSettings.mPackages.get(packageName);
4416        if (ps != null) {
4417            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4418                return null;
4419            }
4420            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4421                return null;
4422            }
4423            if (ps.pkg == null) {
4424                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4425                if (pInfo != null) {
4426                    return pInfo.applicationInfo;
4427                }
4428                return null;
4429            }
4430            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4431                    ps.readUserState(userId), userId);
4432            if (ai != null) {
4433                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4434            }
4435            return ai;
4436        }
4437        return null;
4438    }
4439
4440    @Override
4441    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4442        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4443    }
4444
4445    /**
4446     * Important: The provided filterCallingUid is used exclusively to filter out applications
4447     * that can be seen based on user state. It's typically the original caller uid prior
4448     * to clearing. Because it can only be provided by trusted code, it's value can be
4449     * trusted and will be used as-is; unlike userId which will be validated by this method.
4450     */
4451    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4452            int filterCallingUid, int userId) {
4453        if (!sUserManager.exists(userId)) return null;
4454        flags = updateFlagsForApplication(flags, userId, packageName);
4455        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4456                false /* requireFullPermission */, false /* checkShell */, "get application info");
4457
4458        // writer
4459        synchronized (mPackages) {
4460            // Normalize package name to handle renamed packages and static libs
4461            packageName = resolveInternalPackageNameLPr(packageName,
4462                    PackageManager.VERSION_CODE_HIGHEST);
4463
4464            PackageParser.Package p = mPackages.get(packageName);
4465            if (DEBUG_PACKAGE_INFO) Log.v(
4466                    TAG, "getApplicationInfo " + packageName
4467                    + ": " + p);
4468            if (p != null) {
4469                PackageSetting ps = mSettings.mPackages.get(packageName);
4470                if (ps == null) return null;
4471                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4472                    return null;
4473                }
4474                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4475                    return null;
4476                }
4477                // Note: isEnabledLP() does not apply here - always return info
4478                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4479                        p, flags, ps.readUserState(userId), userId);
4480                if (ai != null) {
4481                    ai.packageName = resolveExternalPackageNameLPr(p);
4482                }
4483                return ai;
4484            }
4485            if ("android".equals(packageName)||"system".equals(packageName)) {
4486                return mAndroidApplication;
4487            }
4488            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4489                // Already generates the external package name
4490                return generateApplicationInfoFromSettingsLPw(packageName,
4491                        flags, filterCallingUid, userId);
4492            }
4493        }
4494        return null;
4495    }
4496
4497    private String normalizePackageNameLPr(String packageName) {
4498        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4499        return normalizedPackageName != null ? normalizedPackageName : packageName;
4500    }
4501
4502    @Override
4503    public void deletePreloadsFileCache() {
4504        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4505            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4506        }
4507        File dir = Environment.getDataPreloadsFileCacheDirectory();
4508        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4509        FileUtils.deleteContents(dir);
4510    }
4511
4512    @Override
4513    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4514            final int storageFlags, final IPackageDataObserver observer) {
4515        mContext.enforceCallingOrSelfPermission(
4516                android.Manifest.permission.CLEAR_APP_CACHE, null);
4517        mHandler.post(() -> {
4518            boolean success = false;
4519            try {
4520                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4521                success = true;
4522            } catch (IOException e) {
4523                Slog.w(TAG, e);
4524            }
4525            if (observer != null) {
4526                try {
4527                    observer.onRemoveCompleted(null, success);
4528                } catch (RemoteException e) {
4529                    Slog.w(TAG, e);
4530                }
4531            }
4532        });
4533    }
4534
4535    @Override
4536    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4537            final int storageFlags, final IntentSender pi) {
4538        mContext.enforceCallingOrSelfPermission(
4539                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4540        mHandler.post(() -> {
4541            boolean success = false;
4542            try {
4543                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4544                success = true;
4545            } catch (IOException e) {
4546                Slog.w(TAG, e);
4547            }
4548            if (pi != null) {
4549                try {
4550                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4551                } catch (SendIntentException e) {
4552                    Slog.w(TAG, e);
4553                }
4554            }
4555        });
4556    }
4557
4558    /**
4559     * Blocking call to clear various types of cached data across the system
4560     * until the requested bytes are available.
4561     */
4562    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4563        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4564        final File file = storage.findPathForUuid(volumeUuid);
4565        if (file.getUsableSpace() >= bytes) return;
4566
4567        if (ENABLE_FREE_CACHE_V2) {
4568            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4569                    volumeUuid);
4570            final boolean aggressive = (storageFlags
4571                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4572            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4573
4574            // 1. Pre-flight to determine if we have any chance to succeed
4575            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4576            if (internalVolume && (aggressive || SystemProperties
4577                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4578                deletePreloadsFileCache();
4579                if (file.getUsableSpace() >= bytes) return;
4580            }
4581
4582            // 3. Consider parsed APK data (aggressive only)
4583            if (internalVolume && aggressive) {
4584                FileUtils.deleteContents(mCacheDir);
4585                if (file.getUsableSpace() >= bytes) return;
4586            }
4587
4588            // 4. Consider cached app data (above quotas)
4589            try {
4590                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4591                        Installer.FLAG_FREE_CACHE_V2);
4592            } catch (InstallerException ignored) {
4593            }
4594            if (file.getUsableSpace() >= bytes) return;
4595
4596            // 5. Consider shared libraries with refcount=0 and age>min cache period
4597            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4598                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4599                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4600                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4601                return;
4602            }
4603
4604            // 6. Consider dexopt output (aggressive only)
4605            // TODO: Implement
4606
4607            // 7. Consider installed instant apps unused longer than min cache period
4608            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4609                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4610                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4611                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4612                return;
4613            }
4614
4615            // 8. Consider cached app data (below quotas)
4616            try {
4617                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4618                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4619            } catch (InstallerException ignored) {
4620            }
4621            if (file.getUsableSpace() >= bytes) return;
4622
4623            // 9. Consider DropBox entries
4624            // TODO: Implement
4625
4626            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4627            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4628                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4629                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4630                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4631                return;
4632            }
4633        } else {
4634            try {
4635                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4636            } catch (InstallerException ignored) {
4637            }
4638            if (file.getUsableSpace() >= bytes) return;
4639        }
4640
4641        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4642    }
4643
4644    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4645            throws IOException {
4646        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4647        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4648
4649        List<VersionedPackage> packagesToDelete = null;
4650        final long now = System.currentTimeMillis();
4651
4652        synchronized (mPackages) {
4653            final int[] allUsers = sUserManager.getUserIds();
4654            final int libCount = mSharedLibraries.size();
4655            for (int i = 0; i < libCount; i++) {
4656                final LongSparseArray<SharedLibraryEntry> versionedLib
4657                        = mSharedLibraries.valueAt(i);
4658                if (versionedLib == null) {
4659                    continue;
4660                }
4661                final int versionCount = versionedLib.size();
4662                for (int j = 0; j < versionCount; j++) {
4663                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4664                    // Skip packages that are not static shared libs.
4665                    if (!libInfo.isStatic()) {
4666                        break;
4667                    }
4668                    // Important: We skip static shared libs used for some user since
4669                    // in such a case we need to keep the APK on the device. The check for
4670                    // a lib being used for any user is performed by the uninstall call.
4671                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4672                    // Resolve the package name - we use synthetic package names internally
4673                    final String internalPackageName = resolveInternalPackageNameLPr(
4674                            declaringPackage.getPackageName(),
4675                            declaringPackage.getLongVersionCode());
4676                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4677                    // Skip unused static shared libs cached less than the min period
4678                    // to prevent pruning a lib needed by a subsequently installed package.
4679                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4680                        continue;
4681                    }
4682                    if (packagesToDelete == null) {
4683                        packagesToDelete = new ArrayList<>();
4684                    }
4685                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4686                            declaringPackage.getLongVersionCode()));
4687                }
4688            }
4689        }
4690
4691        if (packagesToDelete != null) {
4692            final int packageCount = packagesToDelete.size();
4693            for (int i = 0; i < packageCount; i++) {
4694                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4695                // Delete the package synchronously (will fail of the lib used for any user).
4696                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4697                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4698                                == PackageManager.DELETE_SUCCEEDED) {
4699                    if (volume.getUsableSpace() >= neededSpace) {
4700                        return true;
4701                    }
4702                }
4703            }
4704        }
4705
4706        return false;
4707    }
4708
4709    /**
4710     * Update given flags based on encryption status of current user.
4711     */
4712    private int updateFlags(int flags, int userId) {
4713        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4714                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4715            // Caller expressed an explicit opinion about what encryption
4716            // aware/unaware components they want to see, so fall through and
4717            // give them what they want
4718        } else {
4719            // Caller expressed no opinion, so match based on user state
4720            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4721                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4722            } else {
4723                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4724            }
4725        }
4726        return flags;
4727    }
4728
4729    private UserManagerInternal getUserManagerInternal() {
4730        if (mUserManagerInternal == null) {
4731            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4732        }
4733        return mUserManagerInternal;
4734    }
4735
4736    private ActivityManagerInternal getActivityManagerInternal() {
4737        if (mActivityManagerInternal == null) {
4738            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4739        }
4740        return mActivityManagerInternal;
4741    }
4742
4743
4744    private DeviceIdleController.LocalService getDeviceIdleController() {
4745        if (mDeviceIdleController == null) {
4746            mDeviceIdleController =
4747                    LocalServices.getService(DeviceIdleController.LocalService.class);
4748        }
4749        return mDeviceIdleController;
4750    }
4751
4752    /**
4753     * Update given flags when being used to request {@link PackageInfo}.
4754     */
4755    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4756        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4757        boolean triaged = true;
4758        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4759                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4760            // Caller is asking for component details, so they'd better be
4761            // asking for specific encryption matching behavior, or be triaged
4762            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4763                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4764                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4765                triaged = false;
4766            }
4767        }
4768        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4769                | PackageManager.MATCH_SYSTEM_ONLY
4770                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4771            triaged = false;
4772        }
4773        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4774            mPermissionManager.enforceCrossUserPermission(
4775                    Binder.getCallingUid(), userId, false, false,
4776                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4777                    + Debug.getCallers(5));
4778        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4779                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4780            // If the caller wants all packages and has a restricted profile associated with it,
4781            // then match all users. This is to make sure that launchers that need to access work
4782            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4783            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4784            flags |= PackageManager.MATCH_ANY_USER;
4785        }
4786        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4787            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4788                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4789        }
4790        return updateFlags(flags, userId);
4791    }
4792
4793    /**
4794     * Update given flags when being used to request {@link ApplicationInfo}.
4795     */
4796    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4797        return updateFlagsForPackage(flags, userId, cookie);
4798    }
4799
4800    /**
4801     * Update given flags when being used to request {@link ComponentInfo}.
4802     */
4803    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4804        if (cookie instanceof Intent) {
4805            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4806                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4807            }
4808        }
4809
4810        boolean triaged = true;
4811        // Caller is asking for component details, so they'd better be
4812        // asking for specific encryption matching behavior, or be triaged
4813        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4814                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4815                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4816            triaged = false;
4817        }
4818        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4819            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4820                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4821        }
4822
4823        return updateFlags(flags, userId);
4824    }
4825
4826    /**
4827     * Update given intent when being used to request {@link ResolveInfo}.
4828     */
4829    private Intent updateIntentForResolve(Intent intent) {
4830        if (intent.getSelector() != null) {
4831            intent = intent.getSelector();
4832        }
4833        if (DEBUG_PREFERRED) {
4834            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4835        }
4836        return intent;
4837    }
4838
4839    /**
4840     * Update given flags when being used to request {@link ResolveInfo}.
4841     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4842     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4843     * flag set. However, this flag is only honoured in three circumstances:
4844     * <ul>
4845     * <li>when called from a system process</li>
4846     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4847     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4848     * action and a {@code android.intent.category.BROWSABLE} category</li>
4849     * </ul>
4850     */
4851    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4852        return updateFlagsForResolve(flags, userId, intent, callingUid,
4853                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4854    }
4855    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4856            boolean wantInstantApps) {
4857        return updateFlagsForResolve(flags, userId, intent, callingUid,
4858                wantInstantApps, false /*onlyExposedExplicitly*/);
4859    }
4860    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4861            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4862        // Safe mode means we shouldn't match any third-party components
4863        if (mSafeMode) {
4864            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4865        }
4866        if (getInstantAppPackageName(callingUid) != null) {
4867            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4868            if (onlyExposedExplicitly) {
4869                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4870            }
4871            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4872            flags |= PackageManager.MATCH_INSTANT;
4873        } else {
4874            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4875            final boolean allowMatchInstant = wantInstantApps
4876                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4877            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4878                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4879            if (!allowMatchInstant) {
4880                flags &= ~PackageManager.MATCH_INSTANT;
4881            }
4882        }
4883        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4884    }
4885
4886    @Override
4887    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4888        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4889    }
4890
4891    /**
4892     * Important: The provided filterCallingUid is used exclusively to filter out activities
4893     * that can be seen based on user state. It's typically the original caller uid prior
4894     * to clearing. Because it can only be provided by trusted code, it's value can be
4895     * trusted and will be used as-is; unlike userId which will be validated by this method.
4896     */
4897    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4898            int filterCallingUid, int userId) {
4899        if (!sUserManager.exists(userId)) return null;
4900        flags = updateFlagsForComponent(flags, userId, component);
4901
4902        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4903            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4904                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4905        }
4906
4907        synchronized (mPackages) {
4908            PackageParser.Activity a = mActivities.mActivities.get(component);
4909
4910            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4911            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4912                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4913                if (ps == null) return null;
4914                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4915                    return null;
4916                }
4917                return PackageParser.generateActivityInfo(
4918                        a, flags, ps.readUserState(userId), userId);
4919            }
4920            if (mResolveComponentName.equals(component)) {
4921                return PackageParser.generateActivityInfo(
4922                        mResolveActivity, flags, new PackageUserState(), userId);
4923            }
4924        }
4925        return null;
4926    }
4927
4928    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4929        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4930            return false;
4931        }
4932        final long token = Binder.clearCallingIdentity();
4933        try {
4934            final int callingUserId = UserHandle.getUserId(callingUid);
4935            if (ActivityManager.getCurrentUser() != callingUserId) {
4936                return false;
4937            }
4938            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4939        } finally {
4940            Binder.restoreCallingIdentity(token);
4941        }
4942    }
4943
4944    @Override
4945    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4946            String resolvedType) {
4947        synchronized (mPackages) {
4948            if (component.equals(mResolveComponentName)) {
4949                // The resolver supports EVERYTHING!
4950                return true;
4951            }
4952            final int callingUid = Binder.getCallingUid();
4953            final int callingUserId = UserHandle.getUserId(callingUid);
4954            PackageParser.Activity a = mActivities.mActivities.get(component);
4955            if (a == null) {
4956                return false;
4957            }
4958            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4959            if (ps == null) {
4960                return false;
4961            }
4962            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4963                return false;
4964            }
4965            for (int i=0; i<a.intents.size(); i++) {
4966                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4967                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4968                    return true;
4969                }
4970            }
4971            return false;
4972        }
4973    }
4974
4975    @Override
4976    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4977        if (!sUserManager.exists(userId)) return null;
4978        final int callingUid = Binder.getCallingUid();
4979        flags = updateFlagsForComponent(flags, userId, component);
4980        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4981                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4982        synchronized (mPackages) {
4983            PackageParser.Activity a = mReceivers.mActivities.get(component);
4984            if (DEBUG_PACKAGE_INFO) Log.v(
4985                TAG, "getReceiverInfo " + component + ": " + a);
4986            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4987                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4988                if (ps == null) return null;
4989                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4990                    return null;
4991                }
4992                return PackageParser.generateActivityInfo(
4993                        a, flags, ps.readUserState(userId), userId);
4994            }
4995        }
4996        return null;
4997    }
4998
4999    @Override
5000    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
5001            int flags, int userId) {
5002        if (!sUserManager.exists(userId)) return null;
5003        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5004        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5005            return null;
5006        }
5007
5008        flags = updateFlagsForPackage(flags, userId, null);
5009
5010        final boolean canSeeStaticLibraries =
5011                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5012                        == PERMISSION_GRANTED
5013                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5014                        == PERMISSION_GRANTED
5015                || canRequestPackageInstallsInternal(packageName,
5016                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5017                        false  /* throwIfPermNotDeclared*/)
5018                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5019                        == PERMISSION_GRANTED;
5020
5021        synchronized (mPackages) {
5022            List<SharedLibraryInfo> result = null;
5023
5024            final int libCount = mSharedLibraries.size();
5025            for (int i = 0; i < libCount; i++) {
5026                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5027                if (versionedLib == null) {
5028                    continue;
5029                }
5030
5031                final int versionCount = versionedLib.size();
5032                for (int j = 0; j < versionCount; j++) {
5033                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5034                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5035                        break;
5036                    }
5037                    final long identity = Binder.clearCallingIdentity();
5038                    try {
5039                        PackageInfo packageInfo = getPackageInfoVersioned(
5040                                libInfo.getDeclaringPackage(), flags
5041                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5042                        if (packageInfo == null) {
5043                            continue;
5044                        }
5045                    } finally {
5046                        Binder.restoreCallingIdentity(identity);
5047                    }
5048
5049                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5050                            libInfo.getLongVersion(), libInfo.getType(),
5051                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5052                            flags, userId));
5053
5054                    if (result == null) {
5055                        result = new ArrayList<>();
5056                    }
5057                    result.add(resLibInfo);
5058                }
5059            }
5060
5061            return result != null ? new ParceledListSlice<>(result) : null;
5062        }
5063    }
5064
5065    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5066            SharedLibraryInfo libInfo, int flags, int userId) {
5067        List<VersionedPackage> versionedPackages = null;
5068        final int packageCount = mSettings.mPackages.size();
5069        for (int i = 0; i < packageCount; i++) {
5070            PackageSetting ps = mSettings.mPackages.valueAt(i);
5071
5072            if (ps == null) {
5073                continue;
5074            }
5075
5076            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5077                continue;
5078            }
5079
5080            final String libName = libInfo.getName();
5081            if (libInfo.isStatic()) {
5082                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5083                if (libIdx < 0) {
5084                    continue;
5085                }
5086                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5087                    continue;
5088                }
5089                if (versionedPackages == null) {
5090                    versionedPackages = new ArrayList<>();
5091                }
5092                // If the dependent is a static shared lib, use the public package name
5093                String dependentPackageName = ps.name;
5094                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5095                    dependentPackageName = ps.pkg.manifestPackageName;
5096                }
5097                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5098            } else if (ps.pkg != null) {
5099                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5100                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5101                    if (versionedPackages == null) {
5102                        versionedPackages = new ArrayList<>();
5103                    }
5104                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5105                }
5106            }
5107        }
5108
5109        return versionedPackages;
5110    }
5111
5112    @Override
5113    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5114        if (!sUserManager.exists(userId)) return null;
5115        final int callingUid = Binder.getCallingUid();
5116        flags = updateFlagsForComponent(flags, userId, component);
5117        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5118                false /* requireFullPermission */, false /* checkShell */, "get service info");
5119        synchronized (mPackages) {
5120            PackageParser.Service s = mServices.mServices.get(component);
5121            if (DEBUG_PACKAGE_INFO) Log.v(
5122                TAG, "getServiceInfo " + component + ": " + s);
5123            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5124                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5125                if (ps == null) return null;
5126                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5127                    return null;
5128                }
5129                return PackageParser.generateServiceInfo(
5130                        s, flags, ps.readUserState(userId), userId);
5131            }
5132        }
5133        return null;
5134    }
5135
5136    @Override
5137    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5138        if (!sUserManager.exists(userId)) return null;
5139        final int callingUid = Binder.getCallingUid();
5140        flags = updateFlagsForComponent(flags, userId, component);
5141        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5142                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5143        synchronized (mPackages) {
5144            PackageParser.Provider p = mProviders.mProviders.get(component);
5145            if (DEBUG_PACKAGE_INFO) Log.v(
5146                TAG, "getProviderInfo " + component + ": " + p);
5147            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5148                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5149                if (ps == null) return null;
5150                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5151                    return null;
5152                }
5153                return PackageParser.generateProviderInfo(
5154                        p, flags, ps.readUserState(userId), userId);
5155            }
5156        }
5157        return null;
5158    }
5159
5160    @Override
5161    public String[] getSystemSharedLibraryNames() {
5162        // allow instant applications
5163        synchronized (mPackages) {
5164            Set<String> libs = null;
5165            final int libCount = mSharedLibraries.size();
5166            for (int i = 0; i < libCount; i++) {
5167                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5168                if (versionedLib == null) {
5169                    continue;
5170                }
5171                final int versionCount = versionedLib.size();
5172                for (int j = 0; j < versionCount; j++) {
5173                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5174                    if (!libEntry.info.isStatic()) {
5175                        if (libs == null) {
5176                            libs = new ArraySet<>();
5177                        }
5178                        libs.add(libEntry.info.getName());
5179                        break;
5180                    }
5181                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5182                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5183                            UserHandle.getUserId(Binder.getCallingUid()),
5184                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5185                        if (libs == null) {
5186                            libs = new ArraySet<>();
5187                        }
5188                        libs.add(libEntry.info.getName());
5189                        break;
5190                    }
5191                }
5192            }
5193
5194            if (libs != null) {
5195                String[] libsArray = new String[libs.size()];
5196                libs.toArray(libsArray);
5197                return libsArray;
5198            }
5199
5200            return null;
5201        }
5202    }
5203
5204    @Override
5205    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5206        // allow instant applications
5207        synchronized (mPackages) {
5208            return mServicesSystemSharedLibraryPackageName;
5209        }
5210    }
5211
5212    @Override
5213    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5214        // allow instant applications
5215        synchronized (mPackages) {
5216            return mSharedSystemSharedLibraryPackageName;
5217        }
5218    }
5219
5220    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5221        for (int i = userList.length - 1; i >= 0; --i) {
5222            final int userId = userList[i];
5223            // don't add instant app to the list of updates
5224            if (pkgSetting.getInstantApp(userId)) {
5225                continue;
5226            }
5227            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5228            if (changedPackages == null) {
5229                changedPackages = new SparseArray<>();
5230                mChangedPackages.put(userId, changedPackages);
5231            }
5232            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5233            if (sequenceNumbers == null) {
5234                sequenceNumbers = new HashMap<>();
5235                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5236            }
5237            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5238            if (sequenceNumber != null) {
5239                changedPackages.remove(sequenceNumber);
5240            }
5241            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5242            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5243        }
5244        mChangedPackagesSequenceNumber++;
5245    }
5246
5247    @Override
5248    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5249        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5250            return null;
5251        }
5252        synchronized (mPackages) {
5253            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5254                return null;
5255            }
5256            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5257            if (changedPackages == null) {
5258                return null;
5259            }
5260            final List<String> packageNames =
5261                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5262            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5263                final String packageName = changedPackages.get(i);
5264                if (packageName != null) {
5265                    packageNames.add(packageName);
5266                }
5267            }
5268            return packageNames.isEmpty()
5269                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5270        }
5271    }
5272
5273    @Override
5274    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5275        // allow instant applications
5276        ArrayList<FeatureInfo> res;
5277        synchronized (mAvailableFeatures) {
5278            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5279            res.addAll(mAvailableFeatures.values());
5280        }
5281        final FeatureInfo fi = new FeatureInfo();
5282        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5283                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5284        res.add(fi);
5285
5286        return new ParceledListSlice<>(res);
5287    }
5288
5289    @Override
5290    public boolean hasSystemFeature(String name, int version) {
5291        // allow instant applications
5292        synchronized (mAvailableFeatures) {
5293            final FeatureInfo feat = mAvailableFeatures.get(name);
5294            if (feat == null) {
5295                return false;
5296            } else {
5297                return feat.version >= version;
5298            }
5299        }
5300    }
5301
5302    @Override
5303    public int checkPermission(String permName, String pkgName, int userId) {
5304        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5305    }
5306
5307    @Override
5308    public int checkUidPermission(String permName, int uid) {
5309        synchronized (mPackages) {
5310            final String[] packageNames = getPackagesForUid(uid);
5311            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5312                    ? mPackages.get(packageNames[0])
5313                    : null;
5314            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5315        }
5316    }
5317
5318    @Override
5319    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5320        if (UserHandle.getCallingUserId() != userId) {
5321            mContext.enforceCallingPermission(
5322                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5323                    "isPermissionRevokedByPolicy for user " + userId);
5324        }
5325
5326        if (checkPermission(permission, packageName, userId)
5327                == PackageManager.PERMISSION_GRANTED) {
5328            return false;
5329        }
5330
5331        final int callingUid = Binder.getCallingUid();
5332        if (getInstantAppPackageName(callingUid) != null) {
5333            if (!isCallerSameApp(packageName, callingUid)) {
5334                return false;
5335            }
5336        } else {
5337            if (isInstantApp(packageName, userId)) {
5338                return false;
5339            }
5340        }
5341
5342        final long identity = Binder.clearCallingIdentity();
5343        try {
5344            final int flags = getPermissionFlags(permission, packageName, userId);
5345            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5346        } finally {
5347            Binder.restoreCallingIdentity(identity);
5348        }
5349    }
5350
5351    @Override
5352    public String getPermissionControllerPackageName() {
5353        synchronized (mPackages) {
5354            return mRequiredInstallerPackage;
5355        }
5356    }
5357
5358    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5359        return mPermissionManager.addDynamicPermission(
5360                info, async, getCallingUid(), new PermissionCallback() {
5361                    @Override
5362                    public void onPermissionChanged() {
5363                        if (!async) {
5364                            mSettings.writeLPr();
5365                        } else {
5366                            scheduleWriteSettingsLocked();
5367                        }
5368                    }
5369                });
5370    }
5371
5372    @Override
5373    public boolean addPermission(PermissionInfo info) {
5374        synchronized (mPackages) {
5375            return addDynamicPermission(info, false);
5376        }
5377    }
5378
5379    @Override
5380    public boolean addPermissionAsync(PermissionInfo info) {
5381        synchronized (mPackages) {
5382            return addDynamicPermission(info, true);
5383        }
5384    }
5385
5386    @Override
5387    public void removePermission(String permName) {
5388        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5389    }
5390
5391    @Override
5392    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5393        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5394                getCallingUid(), userId, mPermissionCallback);
5395    }
5396
5397    @Override
5398    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5399        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5400                getCallingUid(), userId, mPermissionCallback);
5401    }
5402
5403    @Override
5404    public void resetRuntimePermissions() {
5405        mContext.enforceCallingOrSelfPermission(
5406                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5407                "revokeRuntimePermission");
5408
5409        int callingUid = Binder.getCallingUid();
5410        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5411            mContext.enforceCallingOrSelfPermission(
5412                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5413                    "resetRuntimePermissions");
5414        }
5415
5416        synchronized (mPackages) {
5417            mPermissionManager.updateAllPermissions(
5418                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5419                    mPermissionCallback);
5420            for (int userId : UserManagerService.getInstance().getUserIds()) {
5421                final int packageCount = mPackages.size();
5422                for (int i = 0; i < packageCount; i++) {
5423                    PackageParser.Package pkg = mPackages.valueAt(i);
5424                    if (!(pkg.mExtras instanceof PackageSetting)) {
5425                        continue;
5426                    }
5427                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5428                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5429                }
5430            }
5431        }
5432    }
5433
5434    @Override
5435    public int getPermissionFlags(String permName, String packageName, int userId) {
5436        return mPermissionManager.getPermissionFlags(
5437                permName, packageName, getCallingUid(), userId);
5438    }
5439
5440    @Override
5441    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5442            int flagValues, int userId) {
5443        mPermissionManager.updatePermissionFlags(
5444                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5445                mPermissionCallback);
5446    }
5447
5448    /**
5449     * Update the permission flags for all packages and runtime permissions of a user in order
5450     * to allow device or profile owner to remove POLICY_FIXED.
5451     */
5452    @Override
5453    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5454        synchronized (mPackages) {
5455            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5456                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5457                    mPermissionCallback);
5458            if (changed) {
5459                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5460            }
5461        }
5462    }
5463
5464    @Override
5465    public boolean shouldShowRequestPermissionRationale(String permissionName,
5466            String packageName, int userId) {
5467        if (UserHandle.getCallingUserId() != userId) {
5468            mContext.enforceCallingPermission(
5469                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5470                    "canShowRequestPermissionRationale for user " + userId);
5471        }
5472
5473        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5474        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5475            return false;
5476        }
5477
5478        if (checkPermission(permissionName, packageName, userId)
5479                == PackageManager.PERMISSION_GRANTED) {
5480            return false;
5481        }
5482
5483        final int flags;
5484
5485        final long identity = Binder.clearCallingIdentity();
5486        try {
5487            flags = getPermissionFlags(permissionName,
5488                    packageName, userId);
5489        } finally {
5490            Binder.restoreCallingIdentity(identity);
5491        }
5492
5493        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5494                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5495                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5496
5497        if ((flags & fixedFlags) != 0) {
5498            return false;
5499        }
5500
5501        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5502    }
5503
5504    @Override
5505    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5506        mContext.enforceCallingOrSelfPermission(
5507                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5508                "addOnPermissionsChangeListener");
5509
5510        synchronized (mPackages) {
5511            mOnPermissionChangeListeners.addListenerLocked(listener);
5512        }
5513    }
5514
5515    @Override
5516    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5517        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5518            throw new SecurityException("Instant applications don't have access to this method");
5519        }
5520        synchronized (mPackages) {
5521            mOnPermissionChangeListeners.removeListenerLocked(listener);
5522        }
5523    }
5524
5525    @Override
5526    public boolean isProtectedBroadcast(String actionName) {
5527        // allow instant applications
5528        synchronized (mProtectedBroadcasts) {
5529            if (mProtectedBroadcasts.contains(actionName)) {
5530                return true;
5531            } else if (actionName != null) {
5532                // TODO: remove these terrible hacks
5533                if (actionName.startsWith("android.net.netmon.lingerExpired")
5534                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5535                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5536                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5537                    return true;
5538                }
5539            }
5540        }
5541        return false;
5542    }
5543
5544    @Override
5545    public int checkSignatures(String pkg1, String pkg2) {
5546        synchronized (mPackages) {
5547            final PackageParser.Package p1 = mPackages.get(pkg1);
5548            final PackageParser.Package p2 = mPackages.get(pkg2);
5549            if (p1 == null || p1.mExtras == null
5550                    || p2 == null || p2.mExtras == null) {
5551                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5552            }
5553            final int callingUid = Binder.getCallingUid();
5554            final int callingUserId = UserHandle.getUserId(callingUid);
5555            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5556            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5557            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5558                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5559                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5560            }
5561            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5562        }
5563    }
5564
5565    @Override
5566    public int checkUidSignatures(int uid1, int uid2) {
5567        final int callingUid = Binder.getCallingUid();
5568        final int callingUserId = UserHandle.getUserId(callingUid);
5569        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5570        // Map to base uids.
5571        uid1 = UserHandle.getAppId(uid1);
5572        uid2 = UserHandle.getAppId(uid2);
5573        // reader
5574        synchronized (mPackages) {
5575            Signature[] s1;
5576            Signature[] s2;
5577            Object obj = mSettings.getUserIdLPr(uid1);
5578            if (obj != null) {
5579                if (obj instanceof SharedUserSetting) {
5580                    if (isCallerInstantApp) {
5581                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5582                    }
5583                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5584                } else if (obj instanceof PackageSetting) {
5585                    final PackageSetting ps = (PackageSetting) obj;
5586                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5587                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5588                    }
5589                    s1 = ps.signatures.mSigningDetails.signatures;
5590                } else {
5591                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5592                }
5593            } else {
5594                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5595            }
5596            obj = mSettings.getUserIdLPr(uid2);
5597            if (obj != null) {
5598                if (obj instanceof SharedUserSetting) {
5599                    if (isCallerInstantApp) {
5600                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5601                    }
5602                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5603                } else if (obj instanceof PackageSetting) {
5604                    final PackageSetting ps = (PackageSetting) obj;
5605                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5606                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5607                    }
5608                    s2 = ps.signatures.mSigningDetails.signatures;
5609                } else {
5610                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5611                }
5612            } else {
5613                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5614            }
5615            return compareSignatures(s1, s2);
5616        }
5617    }
5618
5619    @Override
5620    public boolean hasSigningCertificate(
5621            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5622
5623        synchronized (mPackages) {
5624            final PackageParser.Package p = mPackages.get(packageName);
5625            if (p == null || p.mExtras == null) {
5626                return false;
5627            }
5628            final int callingUid = Binder.getCallingUid();
5629            final int callingUserId = UserHandle.getUserId(callingUid);
5630            final PackageSetting ps = (PackageSetting) p.mExtras;
5631            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5632                return false;
5633            }
5634            switch (type) {
5635                case CERT_INPUT_RAW_X509:
5636                    return p.mSigningDetails.hasCertificate(certificate);
5637                case CERT_INPUT_SHA256:
5638                    return p.mSigningDetails.hasSha256Certificate(certificate);
5639                default:
5640                    return false;
5641            }
5642        }
5643    }
5644
5645    @Override
5646    public boolean hasUidSigningCertificate(
5647            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5648        final int callingUid = Binder.getCallingUid();
5649        final int callingUserId = UserHandle.getUserId(callingUid);
5650        // Map to base uids.
5651        uid = UserHandle.getAppId(uid);
5652        // reader
5653        synchronized (mPackages) {
5654            final PackageParser.SigningDetails signingDetails;
5655            final Object obj = mSettings.getUserIdLPr(uid);
5656            if (obj != null) {
5657                if (obj instanceof SharedUserSetting) {
5658                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5659                    if (isCallerInstantApp) {
5660                        return false;
5661                    }
5662                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5663                } else if (obj instanceof PackageSetting) {
5664                    final PackageSetting ps = (PackageSetting) obj;
5665                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5666                        return false;
5667                    }
5668                    signingDetails = ps.signatures.mSigningDetails;
5669                } else {
5670                    return false;
5671                }
5672            } else {
5673                return false;
5674            }
5675            switch (type) {
5676                case CERT_INPUT_RAW_X509:
5677                    return signingDetails.hasCertificate(certificate);
5678                case CERT_INPUT_SHA256:
5679                    return signingDetails.hasSha256Certificate(certificate);
5680                default:
5681                    return false;
5682            }
5683        }
5684    }
5685
5686    /**
5687     * This method should typically only be used when granting or revoking
5688     * permissions, since the app may immediately restart after this call.
5689     * <p>
5690     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5691     * guard your work against the app being relaunched.
5692     */
5693    private void killUid(int appId, int userId, String reason) {
5694        final long identity = Binder.clearCallingIdentity();
5695        try {
5696            IActivityManager am = ActivityManager.getService();
5697            if (am != null) {
5698                try {
5699                    am.killUid(appId, userId, reason);
5700                } catch (RemoteException e) {
5701                    /* ignore - same process */
5702                }
5703            }
5704        } finally {
5705            Binder.restoreCallingIdentity(identity);
5706        }
5707    }
5708
5709    /**
5710     * If the database version for this type of package (internal storage or
5711     * external storage) is less than the version where package signatures
5712     * were updated, return true.
5713     */
5714    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5715        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5716        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5717    }
5718
5719    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5720        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5721        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5722    }
5723
5724    @Override
5725    public List<String> getAllPackages() {
5726        final int callingUid = Binder.getCallingUid();
5727        final int callingUserId = UserHandle.getUserId(callingUid);
5728        synchronized (mPackages) {
5729            if (canViewInstantApps(callingUid, callingUserId)) {
5730                return new ArrayList<String>(mPackages.keySet());
5731            }
5732            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5733            final List<String> result = new ArrayList<>();
5734            if (instantAppPkgName != null) {
5735                // caller is an instant application; filter unexposed applications
5736                for (PackageParser.Package pkg : mPackages.values()) {
5737                    if (!pkg.visibleToInstantApps) {
5738                        continue;
5739                    }
5740                    result.add(pkg.packageName);
5741                }
5742            } else {
5743                // caller is a normal application; filter instant applications
5744                for (PackageParser.Package pkg : mPackages.values()) {
5745                    final PackageSetting ps =
5746                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5747                    if (ps != null
5748                            && ps.getInstantApp(callingUserId)
5749                            && !mInstantAppRegistry.isInstantAccessGranted(
5750                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5751                        continue;
5752                    }
5753                    result.add(pkg.packageName);
5754                }
5755            }
5756            return result;
5757        }
5758    }
5759
5760    @Override
5761    public String[] getPackagesForUid(int uid) {
5762        final int callingUid = Binder.getCallingUid();
5763        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5764        final int userId = UserHandle.getUserId(uid);
5765        uid = UserHandle.getAppId(uid);
5766        // reader
5767        synchronized (mPackages) {
5768            Object obj = mSettings.getUserIdLPr(uid);
5769            if (obj instanceof SharedUserSetting) {
5770                if (isCallerInstantApp) {
5771                    return null;
5772                }
5773                final SharedUserSetting sus = (SharedUserSetting) obj;
5774                final int N = sus.packages.size();
5775                String[] res = new String[N];
5776                final Iterator<PackageSetting> it = sus.packages.iterator();
5777                int i = 0;
5778                while (it.hasNext()) {
5779                    PackageSetting ps = it.next();
5780                    if (ps.getInstalled(userId)) {
5781                        res[i++] = ps.name;
5782                    } else {
5783                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5784                    }
5785                }
5786                return res;
5787            } else if (obj instanceof PackageSetting) {
5788                final PackageSetting ps = (PackageSetting) obj;
5789                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5790                    return new String[]{ps.name};
5791                }
5792            }
5793        }
5794        return null;
5795    }
5796
5797    @Override
5798    public String getNameForUid(int uid) {
5799        final int callingUid = Binder.getCallingUid();
5800        if (getInstantAppPackageName(callingUid) != null) {
5801            return null;
5802        }
5803        synchronized (mPackages) {
5804            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5805            if (obj instanceof SharedUserSetting) {
5806                final SharedUserSetting sus = (SharedUserSetting) obj;
5807                return sus.name + ":" + sus.userId;
5808            } else if (obj instanceof PackageSetting) {
5809                final PackageSetting ps = (PackageSetting) obj;
5810                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5811                    return null;
5812                }
5813                return ps.name;
5814            }
5815            return null;
5816        }
5817    }
5818
5819    @Override
5820    public String[] getNamesForUids(int[] uids) {
5821        if (uids == null || uids.length == 0) {
5822            return null;
5823        }
5824        final int callingUid = Binder.getCallingUid();
5825        if (getInstantAppPackageName(callingUid) != null) {
5826            return null;
5827        }
5828        final String[] names = new String[uids.length];
5829        synchronized (mPackages) {
5830            for (int i = uids.length - 1; i >= 0; i--) {
5831                final int uid = uids[i];
5832                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5833                if (obj instanceof SharedUserSetting) {
5834                    final SharedUserSetting sus = (SharedUserSetting) obj;
5835                    names[i] = "shared:" + sus.name;
5836                } else if (obj instanceof PackageSetting) {
5837                    final PackageSetting ps = (PackageSetting) obj;
5838                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5839                        names[i] = null;
5840                    } else {
5841                        names[i] = ps.name;
5842                    }
5843                } else {
5844                    names[i] = null;
5845                }
5846            }
5847        }
5848        return names;
5849    }
5850
5851    @Override
5852    public int getUidForSharedUser(String sharedUserName) {
5853        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5854            return -1;
5855        }
5856        if (sharedUserName == null) {
5857            return -1;
5858        }
5859        // reader
5860        synchronized (mPackages) {
5861            SharedUserSetting suid;
5862            try {
5863                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5864                if (suid != null) {
5865                    return suid.userId;
5866                }
5867            } catch (PackageManagerException ignore) {
5868                // can't happen, but, still need to catch it
5869            }
5870            return -1;
5871        }
5872    }
5873
5874    @Override
5875    public int getFlagsForUid(int uid) {
5876        final int callingUid = Binder.getCallingUid();
5877        if (getInstantAppPackageName(callingUid) != null) {
5878            return 0;
5879        }
5880        synchronized (mPackages) {
5881            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5882            if (obj instanceof SharedUserSetting) {
5883                final SharedUserSetting sus = (SharedUserSetting) obj;
5884                return sus.pkgFlags;
5885            } else if (obj instanceof PackageSetting) {
5886                final PackageSetting ps = (PackageSetting) obj;
5887                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5888                    return 0;
5889                }
5890                return ps.pkgFlags;
5891            }
5892        }
5893        return 0;
5894    }
5895
5896    @Override
5897    public int getPrivateFlagsForUid(int uid) {
5898        final int callingUid = Binder.getCallingUid();
5899        if (getInstantAppPackageName(callingUid) != null) {
5900            return 0;
5901        }
5902        synchronized (mPackages) {
5903            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5904            if (obj instanceof SharedUserSetting) {
5905                final SharedUserSetting sus = (SharedUserSetting) obj;
5906                return sus.pkgPrivateFlags;
5907            } else if (obj instanceof PackageSetting) {
5908                final PackageSetting ps = (PackageSetting) obj;
5909                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5910                    return 0;
5911                }
5912                return ps.pkgPrivateFlags;
5913            }
5914        }
5915        return 0;
5916    }
5917
5918    @Override
5919    public boolean isUidPrivileged(int uid) {
5920        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5921            return false;
5922        }
5923        uid = UserHandle.getAppId(uid);
5924        // reader
5925        synchronized (mPackages) {
5926            Object obj = mSettings.getUserIdLPr(uid);
5927            if (obj instanceof SharedUserSetting) {
5928                final SharedUserSetting sus = (SharedUserSetting) obj;
5929                final Iterator<PackageSetting> it = sus.packages.iterator();
5930                while (it.hasNext()) {
5931                    if (it.next().isPrivileged()) {
5932                        return true;
5933                    }
5934                }
5935            } else if (obj instanceof PackageSetting) {
5936                final PackageSetting ps = (PackageSetting) obj;
5937                return ps.isPrivileged();
5938            }
5939        }
5940        return false;
5941    }
5942
5943    @Override
5944    public String[] getAppOpPermissionPackages(String permName) {
5945        return mPermissionManager.getAppOpPermissionPackages(permName);
5946    }
5947
5948    @Override
5949    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5950            int flags, int userId) {
5951        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5952                Binder.getCallingUid());
5953    }
5954
5955    /**
5956     * Normally instant apps can only be resolved when they're visible to the caller.
5957     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5958     * since we need to allow the system to start any installed application.
5959     */
5960    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5961            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5962        try {
5963            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5964
5965            if (!sUserManager.exists(userId)) return null;
5966            final int callingUid = Binder.getCallingUid();
5967            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5968            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5969                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5970
5971            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5972            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5973                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5975
5976            final ResolveInfo bestChoice =
5977                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5978            return bestChoice;
5979        } finally {
5980            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5981        }
5982    }
5983
5984    @Override
5985    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5986        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5987            throw new SecurityException(
5988                    "findPersistentPreferredActivity can only be run by the system");
5989        }
5990        if (!sUserManager.exists(userId)) {
5991            return null;
5992        }
5993        final int callingUid = Binder.getCallingUid();
5994        intent = updateIntentForResolve(intent);
5995        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5996        final int flags = updateFlagsForResolve(
5997                0, userId, intent, callingUid, false /*includeInstantApps*/);
5998        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5999                userId);
6000        synchronized (mPackages) {
6001            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6002                    userId);
6003        }
6004    }
6005
6006    @Override
6007    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6008            IntentFilter filter, int match, ComponentName activity) {
6009        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6010            return;
6011        }
6012        final int userId = UserHandle.getCallingUserId();
6013        if (DEBUG_PREFERRED) {
6014            Log.v(TAG, "setLastChosenActivity intent=" + intent
6015                + " resolvedType=" + resolvedType
6016                + " flags=" + flags
6017                + " filter=" + filter
6018                + " match=" + match
6019                + " activity=" + activity);
6020            filter.dump(new PrintStreamPrinter(System.out), "    ");
6021        }
6022        intent.setComponent(null);
6023        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6024                userId);
6025        // Find any earlier preferred or last chosen entries and nuke them
6026        findPreferredActivity(intent, resolvedType,
6027                flags, query, 0, false, true, false, userId);
6028        // Add the new activity as the last chosen for this filter
6029        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6030                "Setting last chosen");
6031    }
6032
6033    @Override
6034    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6035        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6036            return null;
6037        }
6038        final int userId = UserHandle.getCallingUserId();
6039        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6040        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6041                userId);
6042        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6043                false, false, false, userId);
6044    }
6045
6046    /**
6047     * Returns whether or not instant apps have been disabled remotely.
6048     */
6049    private boolean areWebInstantAppsDisabled() {
6050        return mWebInstantAppsDisabled;
6051    }
6052
6053    private boolean isInstantAppResolutionAllowed(
6054            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6055            boolean skipPackageCheck) {
6056        if (mInstantAppResolverConnection == null) {
6057            return false;
6058        }
6059        if (mInstantAppInstallerActivity == null) {
6060            return false;
6061        }
6062        if (intent.getComponent() != null) {
6063            return false;
6064        }
6065        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6066            return false;
6067        }
6068        if (!skipPackageCheck && intent.getPackage() != null) {
6069            return false;
6070        }
6071        if (!intent.isWebIntent()) {
6072            // for non web intents, we should not resolve externally if an app already exists to
6073            // handle it or if the caller didn't explicitly request it.
6074            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6075                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6076                return false;
6077            }
6078        } else {
6079            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6080                return false;
6081            } else if (areWebInstantAppsDisabled()) {
6082                return false;
6083            }
6084        }
6085        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6086        // Or if there's already an ephemeral app installed that handles the action
6087        synchronized (mPackages) {
6088            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6089            for (int n = 0; n < count; n++) {
6090                final ResolveInfo info = resolvedActivities.get(n);
6091                final String packageName = info.activityInfo.packageName;
6092                final PackageSetting ps = mSettings.mPackages.get(packageName);
6093                if (ps != null) {
6094                    // only check domain verification status if the app is not a browser
6095                    if (!info.handleAllWebDataURI) {
6096                        // Try to get the status from User settings first
6097                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6098                        final int status = (int) (packedStatus >> 32);
6099                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6100                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6101                            if (DEBUG_INSTANT) {
6102                                Slog.v(TAG, "DENY instant app;"
6103                                    + " pkg: " + packageName + ", status: " + status);
6104                            }
6105                            return false;
6106                        }
6107                    }
6108                    if (ps.getInstantApp(userId)) {
6109                        if (DEBUG_INSTANT) {
6110                            Slog.v(TAG, "DENY instant app installed;"
6111                                    + " pkg: " + packageName);
6112                        }
6113                        return false;
6114                    }
6115                }
6116            }
6117        }
6118        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6119        return true;
6120    }
6121
6122    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6123            Intent origIntent, String resolvedType, String callingPackage,
6124            Bundle verificationBundle, int userId) {
6125        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6126                new InstantAppRequest(responseObj, origIntent, resolvedType,
6127                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6128        mHandler.sendMessage(msg);
6129    }
6130
6131    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6132            int flags, List<ResolveInfo> query, int userId) {
6133        if (query != null) {
6134            final int N = query.size();
6135            if (N == 1) {
6136                return query.get(0);
6137            } else if (N > 1) {
6138                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6139                // If there is more than one activity with the same priority,
6140                // then let the user decide between them.
6141                ResolveInfo r0 = query.get(0);
6142                ResolveInfo r1 = query.get(1);
6143                if (DEBUG_INTENT_MATCHING || debug) {
6144                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6145                            + r1.activityInfo.name + "=" + r1.priority);
6146                }
6147                // If the first activity has a higher priority, or a different
6148                // default, then it is always desirable to pick it.
6149                if (r0.priority != r1.priority
6150                        || r0.preferredOrder != r1.preferredOrder
6151                        || r0.isDefault != r1.isDefault) {
6152                    return query.get(0);
6153                }
6154                // If we have saved a preference for a preferred activity for
6155                // this Intent, use that.
6156                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6157                        flags, query, r0.priority, true, false, debug, userId);
6158                if (ri != null) {
6159                    return ri;
6160                }
6161                // If we have an ephemeral app, use it
6162                for (int i = 0; i < N; i++) {
6163                    ri = query.get(i);
6164                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6165                        final String packageName = ri.activityInfo.packageName;
6166                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6167                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6168                        final int status = (int)(packedStatus >> 32);
6169                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6170                            return ri;
6171                        }
6172                    }
6173                }
6174                ri = new ResolveInfo(mResolveInfo);
6175                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6176                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6177                // If all of the options come from the same package, show the application's
6178                // label and icon instead of the generic resolver's.
6179                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6180                // and then throw away the ResolveInfo itself, meaning that the caller loses
6181                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6182                // a fallback for this case; we only set the target package's resources on
6183                // the ResolveInfo, not the ActivityInfo.
6184                final String intentPackage = intent.getPackage();
6185                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6186                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6187                    ri.resolvePackageName = intentPackage;
6188                    if (userNeedsBadging(userId)) {
6189                        ri.noResourceId = true;
6190                    } else {
6191                        ri.icon = appi.icon;
6192                    }
6193                    ri.iconResourceId = appi.icon;
6194                    ri.labelRes = appi.labelRes;
6195                }
6196                ri.activityInfo.applicationInfo = new ApplicationInfo(
6197                        ri.activityInfo.applicationInfo);
6198                if (userId != 0) {
6199                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6200                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6201                }
6202                // Make sure that the resolver is displayable in car mode
6203                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6204                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6205                return ri;
6206            }
6207        }
6208        return null;
6209    }
6210
6211    /**
6212     * Return true if the given list is not empty and all of its contents have
6213     * an activityInfo with the given package name.
6214     */
6215    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6216        if (ArrayUtils.isEmpty(list)) {
6217            return false;
6218        }
6219        for (int i = 0, N = list.size(); i < N; i++) {
6220            final ResolveInfo ri = list.get(i);
6221            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6222            if (ai == null || !packageName.equals(ai.packageName)) {
6223                return false;
6224            }
6225        }
6226        return true;
6227    }
6228
6229    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6230            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6231        final int N = query.size();
6232        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6233                .get(userId);
6234        // Get the list of persistent preferred activities that handle the intent
6235        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6236        List<PersistentPreferredActivity> pprefs = ppir != null
6237                ? ppir.queryIntent(intent, resolvedType,
6238                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6239                        userId)
6240                : null;
6241        if (pprefs != null && pprefs.size() > 0) {
6242            final int M = pprefs.size();
6243            for (int i=0; i<M; i++) {
6244                final PersistentPreferredActivity ppa = pprefs.get(i);
6245                if (DEBUG_PREFERRED || debug) {
6246                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6247                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6248                            + "\n  component=" + ppa.mComponent);
6249                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6250                }
6251                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6252                        flags | MATCH_DISABLED_COMPONENTS, userId);
6253                if (DEBUG_PREFERRED || debug) {
6254                    Slog.v(TAG, "Found persistent preferred activity:");
6255                    if (ai != null) {
6256                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6257                    } else {
6258                        Slog.v(TAG, "  null");
6259                    }
6260                }
6261                if (ai == null) {
6262                    // This previously registered persistent preferred activity
6263                    // component is no longer known. Ignore it and do NOT remove it.
6264                    continue;
6265                }
6266                for (int j=0; j<N; j++) {
6267                    final ResolveInfo ri = query.get(j);
6268                    if (!ri.activityInfo.applicationInfo.packageName
6269                            .equals(ai.applicationInfo.packageName)) {
6270                        continue;
6271                    }
6272                    if (!ri.activityInfo.name.equals(ai.name)) {
6273                        continue;
6274                    }
6275                    //  Found a persistent preference that can handle the intent.
6276                    if (DEBUG_PREFERRED || debug) {
6277                        Slog.v(TAG, "Returning persistent preferred activity: " +
6278                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6279                    }
6280                    return ri;
6281                }
6282            }
6283        }
6284        return null;
6285    }
6286
6287    // TODO: handle preferred activities missing while user has amnesia
6288    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6289            List<ResolveInfo> query, int priority, boolean always,
6290            boolean removeMatches, boolean debug, int userId) {
6291        if (!sUserManager.exists(userId)) return null;
6292        final int callingUid = Binder.getCallingUid();
6293        flags = updateFlagsForResolve(
6294                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6295        intent = updateIntentForResolve(intent);
6296        // writer
6297        synchronized (mPackages) {
6298            // Try to find a matching persistent preferred activity.
6299            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6300                    debug, userId);
6301
6302            // If a persistent preferred activity matched, use it.
6303            if (pri != null) {
6304                return pri;
6305            }
6306
6307            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6308            // Get the list of preferred activities that handle the intent
6309            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6310            List<PreferredActivity> prefs = pir != null
6311                    ? pir.queryIntent(intent, resolvedType,
6312                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6313                            userId)
6314                    : null;
6315            if (prefs != null && prefs.size() > 0) {
6316                boolean changed = false;
6317                try {
6318                    // First figure out how good the original match set is.
6319                    // We will only allow preferred activities that came
6320                    // from the same match quality.
6321                    int match = 0;
6322
6323                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6324
6325                    final int N = query.size();
6326                    for (int j=0; j<N; j++) {
6327                        final ResolveInfo ri = query.get(j);
6328                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6329                                + ": 0x" + Integer.toHexString(match));
6330                        if (ri.match > match) {
6331                            match = ri.match;
6332                        }
6333                    }
6334
6335                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6336                            + Integer.toHexString(match));
6337
6338                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6339                    final int M = prefs.size();
6340                    for (int i=0; i<M; i++) {
6341                        final PreferredActivity pa = prefs.get(i);
6342                        if (DEBUG_PREFERRED || debug) {
6343                            Slog.v(TAG, "Checking PreferredActivity ds="
6344                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6345                                    + "\n  component=" + pa.mPref.mComponent);
6346                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6347                        }
6348                        if (pa.mPref.mMatch != match) {
6349                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6350                                    + Integer.toHexString(pa.mPref.mMatch));
6351                            continue;
6352                        }
6353                        // If it's not an "always" type preferred activity and that's what we're
6354                        // looking for, skip it.
6355                        if (always && !pa.mPref.mAlways) {
6356                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6357                            continue;
6358                        }
6359                        final ActivityInfo ai = getActivityInfo(
6360                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6361                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6362                                userId);
6363                        if (DEBUG_PREFERRED || debug) {
6364                            Slog.v(TAG, "Found preferred activity:");
6365                            if (ai != null) {
6366                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6367                            } else {
6368                                Slog.v(TAG, "  null");
6369                            }
6370                        }
6371                        if (ai == null) {
6372                            // This previously registered preferred activity
6373                            // component is no longer known.  Most likely an update
6374                            // to the app was installed and in the new version this
6375                            // component no longer exists.  Clean it up by removing
6376                            // it from the preferred activities list, and skip it.
6377                            Slog.w(TAG, "Removing dangling preferred activity: "
6378                                    + pa.mPref.mComponent);
6379                            pir.removeFilter(pa);
6380                            changed = true;
6381                            continue;
6382                        }
6383                        for (int j=0; j<N; j++) {
6384                            final ResolveInfo ri = query.get(j);
6385                            if (!ri.activityInfo.applicationInfo.packageName
6386                                    .equals(ai.applicationInfo.packageName)) {
6387                                continue;
6388                            }
6389                            if (!ri.activityInfo.name.equals(ai.name)) {
6390                                continue;
6391                            }
6392
6393                            if (removeMatches) {
6394                                pir.removeFilter(pa);
6395                                changed = true;
6396                                if (DEBUG_PREFERRED) {
6397                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6398                                }
6399                                break;
6400                            }
6401
6402                            // Okay we found a previously set preferred or last chosen app.
6403                            // If the result set is different from when this
6404                            // was created, and is not a subset of the preferred set, we need to
6405                            // clear it and re-ask the user their preference, if we're looking for
6406                            // an "always" type entry.
6407                            if (always && !pa.mPref.sameSet(query)) {
6408                                if (pa.mPref.isSuperset(query)) {
6409                                    // some components of the set are no longer present in
6410                                    // the query, but the preferred activity can still be reused
6411                                    if (DEBUG_PREFERRED) {
6412                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6413                                                + " still valid as only non-preferred components"
6414                                                + " were removed for " + intent + " type "
6415                                                + resolvedType);
6416                                    }
6417                                    // remove obsolete components and re-add the up-to-date filter
6418                                    PreferredActivity freshPa = new PreferredActivity(pa,
6419                                            pa.mPref.mMatch,
6420                                            pa.mPref.discardObsoleteComponents(query),
6421                                            pa.mPref.mComponent,
6422                                            pa.mPref.mAlways);
6423                                    pir.removeFilter(pa);
6424                                    pir.addFilter(freshPa);
6425                                    changed = true;
6426                                } else {
6427                                    Slog.i(TAG,
6428                                            "Result set changed, dropping preferred activity for "
6429                                                    + intent + " type " + resolvedType);
6430                                    if (DEBUG_PREFERRED) {
6431                                        Slog.v(TAG, "Removing preferred activity since set changed "
6432                                                + pa.mPref.mComponent);
6433                                    }
6434                                    pir.removeFilter(pa);
6435                                    // Re-add the filter as a "last chosen" entry (!always)
6436                                    PreferredActivity lastChosen = new PreferredActivity(
6437                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6438                                    pir.addFilter(lastChosen);
6439                                    changed = true;
6440                                    return null;
6441                                }
6442                            }
6443
6444                            // Yay! Either the set matched or we're looking for the last chosen
6445                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6446                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6447                            return ri;
6448                        }
6449                    }
6450                } finally {
6451                    if (changed) {
6452                        if (DEBUG_PREFERRED) {
6453                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6454                        }
6455                        scheduleWritePackageRestrictionsLocked(userId);
6456                    }
6457                }
6458            }
6459        }
6460        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6461        return null;
6462    }
6463
6464    /*
6465     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6466     */
6467    @Override
6468    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6469            int targetUserId) {
6470        mContext.enforceCallingOrSelfPermission(
6471                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6472        List<CrossProfileIntentFilter> matches =
6473                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6474        if (matches != null) {
6475            int size = matches.size();
6476            for (int i = 0; i < size; i++) {
6477                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6478            }
6479        }
6480        if (intent.hasWebURI()) {
6481            // cross-profile app linking works only towards the parent.
6482            final int callingUid = Binder.getCallingUid();
6483            final UserInfo parent = getProfileParent(sourceUserId);
6484            synchronized(mPackages) {
6485                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6486                        false /*includeInstantApps*/);
6487                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6488                        intent, resolvedType, flags, sourceUserId, parent.id);
6489                return xpDomainInfo != null;
6490            }
6491        }
6492        return false;
6493    }
6494
6495    private UserInfo getProfileParent(int userId) {
6496        final long identity = Binder.clearCallingIdentity();
6497        try {
6498            return sUserManager.getProfileParent(userId);
6499        } finally {
6500            Binder.restoreCallingIdentity(identity);
6501        }
6502    }
6503
6504    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6505            String resolvedType, int userId) {
6506        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6507        if (resolver != null) {
6508            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6509        }
6510        return null;
6511    }
6512
6513    @Override
6514    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6515            String resolvedType, int flags, int userId) {
6516        try {
6517            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6518
6519            return new ParceledListSlice<>(
6520                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6521        } finally {
6522            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6523        }
6524    }
6525
6526    /**
6527     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6528     * instant, returns {@code null}.
6529     */
6530    private String getInstantAppPackageName(int callingUid) {
6531        synchronized (mPackages) {
6532            // If the caller is an isolated app use the owner's uid for the lookup.
6533            if (Process.isIsolated(callingUid)) {
6534                callingUid = mIsolatedOwners.get(callingUid);
6535            }
6536            final int appId = UserHandle.getAppId(callingUid);
6537            final Object obj = mSettings.getUserIdLPr(appId);
6538            if (obj instanceof PackageSetting) {
6539                final PackageSetting ps = (PackageSetting) obj;
6540                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6541                return isInstantApp ? ps.pkg.packageName : null;
6542            }
6543        }
6544        return null;
6545    }
6546
6547    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6548            String resolvedType, int flags, int userId) {
6549        return queryIntentActivitiesInternal(
6550                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6551                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6552    }
6553
6554    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6555            String resolvedType, int flags, int filterCallingUid, int userId,
6556            boolean resolveForStart, boolean allowDynamicSplits) {
6557        if (!sUserManager.exists(userId)) return Collections.emptyList();
6558        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6559        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6560                false /* requireFullPermission */, false /* checkShell */,
6561                "query intent activities");
6562        final String pkgName = intent.getPackage();
6563        ComponentName comp = intent.getComponent();
6564        if (comp == null) {
6565            if (intent.getSelector() != null) {
6566                intent = intent.getSelector();
6567                comp = intent.getComponent();
6568            }
6569        }
6570
6571        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6572                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6573        if (comp != null) {
6574            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6575            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6576            if (ai != null) {
6577                // When specifying an explicit component, we prevent the activity from being
6578                // used when either 1) the calling package is normal and the activity is within
6579                // an ephemeral application or 2) the calling package is ephemeral and the
6580                // activity is not visible to ephemeral applications.
6581                final boolean matchInstantApp =
6582                        (flags & PackageManager.MATCH_INSTANT) != 0;
6583                final boolean matchVisibleToInstantAppOnly =
6584                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6585                final boolean matchExplicitlyVisibleOnly =
6586                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6587                final boolean isCallerInstantApp =
6588                        instantAppPkgName != null;
6589                final boolean isTargetSameInstantApp =
6590                        comp.getPackageName().equals(instantAppPkgName);
6591                final boolean isTargetInstantApp =
6592                        (ai.applicationInfo.privateFlags
6593                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6594                final boolean isTargetVisibleToInstantApp =
6595                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6596                final boolean isTargetExplicitlyVisibleToInstantApp =
6597                        isTargetVisibleToInstantApp
6598                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6599                final boolean isTargetHiddenFromInstantApp =
6600                        !isTargetVisibleToInstantApp
6601                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6602                final boolean blockResolution =
6603                        !isTargetSameInstantApp
6604                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6605                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6606                                        && isTargetHiddenFromInstantApp));
6607                if (!blockResolution) {
6608                    final ResolveInfo ri = new ResolveInfo();
6609                    ri.activityInfo = ai;
6610                    list.add(ri);
6611                }
6612            }
6613            return applyPostResolutionFilter(
6614                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6615        }
6616
6617        // reader
6618        boolean sortResult = false;
6619        boolean addInstant = false;
6620        List<ResolveInfo> result;
6621        synchronized (mPackages) {
6622            if (pkgName == null) {
6623                List<CrossProfileIntentFilter> matchingFilters =
6624                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6625                // Check for results that need to skip the current profile.
6626                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6627                        resolvedType, flags, userId);
6628                if (xpResolveInfo != null) {
6629                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6630                    xpResult.add(xpResolveInfo);
6631                    return applyPostResolutionFilter(
6632                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6633                            allowDynamicSplits, filterCallingUid, userId, intent);
6634                }
6635
6636                // Check for results in the current profile.
6637                result = filterIfNotSystemUser(mActivities.queryIntent(
6638                        intent, resolvedType, flags, userId), userId);
6639                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6640                        false /*skipPackageCheck*/);
6641                // Check for cross profile results.
6642                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6643                xpResolveInfo = queryCrossProfileIntents(
6644                        matchingFilters, intent, resolvedType, flags, userId,
6645                        hasNonNegativePriorityResult);
6646                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6647                    boolean isVisibleToUser = filterIfNotSystemUser(
6648                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6649                    if (isVisibleToUser) {
6650                        result.add(xpResolveInfo);
6651                        sortResult = true;
6652                    }
6653                }
6654                if (intent.hasWebURI()) {
6655                    CrossProfileDomainInfo xpDomainInfo = null;
6656                    final UserInfo parent = getProfileParent(userId);
6657                    if (parent != null) {
6658                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6659                                flags, userId, parent.id);
6660                    }
6661                    if (xpDomainInfo != null) {
6662                        if (xpResolveInfo != null) {
6663                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6664                            // in the result.
6665                            result.remove(xpResolveInfo);
6666                        }
6667                        if (result.size() == 0 && !addInstant) {
6668                            // No result in current profile, but found candidate in parent user.
6669                            // And we are not going to add emphemeral app, so we can return the
6670                            // result straight away.
6671                            result.add(xpDomainInfo.resolveInfo);
6672                            return applyPostResolutionFilter(result, instantAppPkgName,
6673                                    allowDynamicSplits, filterCallingUid, userId, intent);
6674                        }
6675                    } else if (result.size() <= 1 && !addInstant) {
6676                        // No result in parent user and <= 1 result in current profile, and we
6677                        // are not going to add emphemeral app, so we can return the result without
6678                        // further processing.
6679                        return applyPostResolutionFilter(result, instantAppPkgName,
6680                                allowDynamicSplits, filterCallingUid, userId, intent);
6681                    }
6682                    // We have more than one candidate (combining results from current and parent
6683                    // profile), so we need filtering and sorting.
6684                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6685                            intent, flags, result, xpDomainInfo, userId);
6686                    sortResult = true;
6687                }
6688            } else {
6689                final PackageParser.Package pkg = mPackages.get(pkgName);
6690                result = null;
6691                if (pkg != null) {
6692                    result = filterIfNotSystemUser(
6693                            mActivities.queryIntentForPackage(
6694                                    intent, resolvedType, flags, pkg.activities, userId),
6695                            userId);
6696                }
6697                if (result == null || result.size() == 0) {
6698                    // the caller wants to resolve for a particular package; however, there
6699                    // were no installed results, so, try to find an ephemeral result
6700                    addInstant = isInstantAppResolutionAllowed(
6701                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6702                    if (result == null) {
6703                        result = new ArrayList<>();
6704                    }
6705                }
6706            }
6707        }
6708        if (addInstant) {
6709            result = maybeAddInstantAppInstaller(
6710                    result, intent, resolvedType, flags, userId, resolveForStart);
6711        }
6712        if (sortResult) {
6713            Collections.sort(result, mResolvePrioritySorter);
6714        }
6715        return applyPostResolutionFilter(
6716                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6717    }
6718
6719    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6720            String resolvedType, int flags, int userId, boolean resolveForStart) {
6721        // first, check to see if we've got an instant app already installed
6722        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6723        ResolveInfo localInstantApp = null;
6724        boolean blockResolution = false;
6725        if (!alreadyResolvedLocally) {
6726            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6727                    flags
6728                        | PackageManager.GET_RESOLVED_FILTER
6729                        | PackageManager.MATCH_INSTANT
6730                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6731                    userId);
6732            for (int i = instantApps.size() - 1; i >= 0; --i) {
6733                final ResolveInfo info = instantApps.get(i);
6734                final String packageName = info.activityInfo.packageName;
6735                final PackageSetting ps = mSettings.mPackages.get(packageName);
6736                if (ps.getInstantApp(userId)) {
6737                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6738                    final int status = (int)(packedStatus >> 32);
6739                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6740                        // there's a local instant application installed, but, the user has
6741                        // chosen to never use it; skip resolution and don't acknowledge
6742                        // an instant application is even available
6743                        if (DEBUG_INSTANT) {
6744                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6745                        }
6746                        blockResolution = true;
6747                        break;
6748                    } else {
6749                        // we have a locally installed instant application; skip resolution
6750                        // but acknowledge there's an instant application available
6751                        if (DEBUG_INSTANT) {
6752                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6753                        }
6754                        localInstantApp = info;
6755                        break;
6756                    }
6757                }
6758            }
6759        }
6760        // no app installed, let's see if one's available
6761        AuxiliaryResolveInfo auxiliaryResponse = null;
6762        if (!blockResolution) {
6763            if (localInstantApp == null) {
6764                // we don't have an instant app locally, resolve externally
6765                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6766                final InstantAppRequest requestObject = new InstantAppRequest(
6767                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6768                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6769                        resolveForStart);
6770                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6771                        mInstantAppResolverConnection, requestObject);
6772                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6773            } else {
6774                // we have an instant application locally, but, we can't admit that since
6775                // callers shouldn't be able to determine prior browsing. create a dummy
6776                // auxiliary response so the downstream code behaves as if there's an
6777                // instant application available externally. when it comes time to start
6778                // the instant application, we'll do the right thing.
6779                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6780                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6781                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6782            }
6783        }
6784        if (intent.isWebIntent() && auxiliaryResponse == null) {
6785            return result;
6786        }
6787        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6788        if (ps == null
6789                || ps.getUserState().get(userId) == null
6790                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6791            return result;
6792        }
6793        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6794        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6795                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6796        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6797                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6798        // add a non-generic filter
6799        ephemeralInstaller.filter = new IntentFilter();
6800        if (intent.getAction() != null) {
6801            ephemeralInstaller.filter.addAction(intent.getAction());
6802        }
6803        if (intent.getData() != null && intent.getData().getPath() != null) {
6804            ephemeralInstaller.filter.addDataPath(
6805                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6806        }
6807        ephemeralInstaller.isInstantAppAvailable = true;
6808        // make sure this resolver is the default
6809        ephemeralInstaller.isDefault = true;
6810        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6811        if (DEBUG_INSTANT) {
6812            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6813        }
6814
6815        result.add(ephemeralInstaller);
6816        return result;
6817    }
6818
6819    private static class CrossProfileDomainInfo {
6820        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6821        ResolveInfo resolveInfo;
6822        /* Best domain verification status of the activities found in the other profile */
6823        int bestDomainVerificationStatus;
6824    }
6825
6826    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6827            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6828        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6829                sourceUserId)) {
6830            return null;
6831        }
6832        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6833                resolvedType, flags, parentUserId);
6834
6835        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6836            return null;
6837        }
6838        CrossProfileDomainInfo result = null;
6839        int size = resultTargetUser.size();
6840        for (int i = 0; i < size; i++) {
6841            ResolveInfo riTargetUser = resultTargetUser.get(i);
6842            // Intent filter verification is only for filters that specify a host. So don't return
6843            // those that handle all web uris.
6844            if (riTargetUser.handleAllWebDataURI) {
6845                continue;
6846            }
6847            String packageName = riTargetUser.activityInfo.packageName;
6848            PackageSetting ps = mSettings.mPackages.get(packageName);
6849            if (ps == null) {
6850                continue;
6851            }
6852            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6853            int status = (int)(verificationState >> 32);
6854            if (result == null) {
6855                result = new CrossProfileDomainInfo();
6856                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6857                        sourceUserId, parentUserId);
6858                result.bestDomainVerificationStatus = status;
6859            } else {
6860                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6861                        result.bestDomainVerificationStatus);
6862            }
6863        }
6864        // Don't consider matches with status NEVER across profiles.
6865        if (result != null && result.bestDomainVerificationStatus
6866                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6867            return null;
6868        }
6869        return result;
6870    }
6871
6872    /**
6873     * Verification statuses are ordered from the worse to the best, except for
6874     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6875     */
6876    private int bestDomainVerificationStatus(int status1, int status2) {
6877        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6878            return status2;
6879        }
6880        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6881            return status1;
6882        }
6883        return (int) MathUtils.max(status1, status2);
6884    }
6885
6886    private boolean isUserEnabled(int userId) {
6887        long callingId = Binder.clearCallingIdentity();
6888        try {
6889            UserInfo userInfo = sUserManager.getUserInfo(userId);
6890            return userInfo != null && userInfo.isEnabled();
6891        } finally {
6892            Binder.restoreCallingIdentity(callingId);
6893        }
6894    }
6895
6896    /**
6897     * Filter out activities with systemUserOnly flag set, when current user is not System.
6898     *
6899     * @return filtered list
6900     */
6901    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6902        if (userId == UserHandle.USER_SYSTEM) {
6903            return resolveInfos;
6904        }
6905        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6906            ResolveInfo info = resolveInfos.get(i);
6907            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6908                resolveInfos.remove(i);
6909            }
6910        }
6911        return resolveInfos;
6912    }
6913
6914    /**
6915     * Filters out ephemeral activities.
6916     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6917     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6918     *
6919     * @param resolveInfos The pre-filtered list of resolved activities
6920     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6921     *          is performed.
6922     * @param intent
6923     * @return A filtered list of resolved activities.
6924     */
6925    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6926            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6927            Intent intent) {
6928        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6929        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6930            final ResolveInfo info = resolveInfos.get(i);
6931            // remove locally resolved instant app web results when disabled
6932            if (info.isInstantAppAvailable && blockInstant) {
6933                resolveInfos.remove(i);
6934                continue;
6935            }
6936            // allow activities that are defined in the provided package
6937            if (allowDynamicSplits
6938                    && info.activityInfo != null
6939                    && info.activityInfo.splitName != null
6940                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6941                            info.activityInfo.splitName)) {
6942                if (mInstantAppInstallerActivity == null) {
6943                    if (DEBUG_INSTALL) {
6944                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6945                    }
6946                    resolveInfos.remove(i);
6947                    continue;
6948                }
6949                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6950                    resolveInfos.remove(i);
6951                    continue;
6952                }
6953                // requested activity is defined in a split that hasn't been installed yet.
6954                // add the installer to the resolve list
6955                if (DEBUG_INSTALL) {
6956                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6957                }
6958                final ResolveInfo installerInfo = new ResolveInfo(
6959                        mInstantAppInstallerInfo);
6960                final ComponentName installFailureActivity = findInstallFailureActivity(
6961                        info.activityInfo.packageName,  filterCallingUid, userId);
6962                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6963                        installFailureActivity,
6964                        info.activityInfo.packageName,
6965                        info.activityInfo.applicationInfo.longVersionCode,
6966                        info.activityInfo.splitName);
6967                // add a non-generic filter
6968                installerInfo.filter = new IntentFilter();
6969
6970                // This resolve info may appear in the chooser UI, so let us make it
6971                // look as the one it replaces as far as the user is concerned which
6972                // requires loading the correct label and icon for the resolve info.
6973                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6974                installerInfo.labelRes = info.resolveLabelResId();
6975                installerInfo.icon = info.resolveIconResId();
6976                installerInfo.isInstantAppAvailable = true;
6977                resolveInfos.set(i, installerInfo);
6978                continue;
6979            }
6980            // caller is a full app, don't need to apply any other filtering
6981            if (ephemeralPkgName == null) {
6982                continue;
6983            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6984                // caller is same app; don't need to apply any other filtering
6985                continue;
6986            }
6987            // allow activities that have been explicitly exposed to ephemeral apps
6988            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6989            if (!isEphemeralApp
6990                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6991                continue;
6992            }
6993            resolveInfos.remove(i);
6994        }
6995        return resolveInfos;
6996    }
6997
6998    /**
6999     * Returns the activity component that can handle install failures.
7000     * <p>By default, the instant application installer handles failures. However, an
7001     * application may want to handle failures on its own. Applications do this by
7002     * creating an activity with an intent filter that handles the action
7003     * {@link Intent#ACTION_INSTALL_FAILURE}.
7004     */
7005    private @Nullable ComponentName findInstallFailureActivity(
7006            String packageName, int filterCallingUid, int userId) {
7007        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7008        failureActivityIntent.setPackage(packageName);
7009        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7010        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7011                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7012                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7013        final int NR = result.size();
7014        if (NR > 0) {
7015            for (int i = 0; i < NR; i++) {
7016                final ResolveInfo info = result.get(i);
7017                if (info.activityInfo.splitName != null) {
7018                    continue;
7019                }
7020                return new ComponentName(packageName, info.activityInfo.name);
7021            }
7022        }
7023        return null;
7024    }
7025
7026    /**
7027     * @param resolveInfos list of resolve infos in descending priority order
7028     * @return if the list contains a resolve info with non-negative priority
7029     */
7030    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7031        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7032    }
7033
7034    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7035            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7036            int userId) {
7037        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7038
7039        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7040            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7041                    candidates.size());
7042        }
7043
7044        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7045        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7046        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7047        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7048        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7049        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7050
7051        synchronized (mPackages) {
7052            final int count = candidates.size();
7053            // First, try to use linked apps. Partition the candidates into four lists:
7054            // one for the final results, one for the "do not use ever", one for "undefined status"
7055            // and finally one for "browser app type".
7056            for (int n=0; n<count; n++) {
7057                ResolveInfo info = candidates.get(n);
7058                String packageName = info.activityInfo.packageName;
7059                PackageSetting ps = mSettings.mPackages.get(packageName);
7060                if (ps != null) {
7061                    // Add to the special match all list (Browser use case)
7062                    if (info.handleAllWebDataURI) {
7063                        matchAllList.add(info);
7064                        continue;
7065                    }
7066                    // Try to get the status from User settings first
7067                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7068                    int status = (int)(packedStatus >> 32);
7069                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7070                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7071                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7072                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7073                                    + " : linkgen=" + linkGeneration);
7074                        }
7075                        // Use link-enabled generation as preferredOrder, i.e.
7076                        // prefer newly-enabled over earlier-enabled.
7077                        info.preferredOrder = linkGeneration;
7078                        alwaysList.add(info);
7079                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7080                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7081                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7082                        }
7083                        neverList.add(info);
7084                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7085                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7086                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7087                        }
7088                        alwaysAskList.add(info);
7089                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7090                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7091                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7092                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7093                        }
7094                        undefinedList.add(info);
7095                    }
7096                }
7097            }
7098
7099            // We'll want to include browser possibilities in a few cases
7100            boolean includeBrowser = false;
7101
7102            // First try to add the "always" resolution(s) for the current user, if any
7103            if (alwaysList.size() > 0) {
7104                result.addAll(alwaysList);
7105            } else {
7106                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7107                result.addAll(undefinedList);
7108                // Maybe add one for the other profile.
7109                if (xpDomainInfo != null && (
7110                        xpDomainInfo.bestDomainVerificationStatus
7111                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7112                    result.add(xpDomainInfo.resolveInfo);
7113                }
7114                includeBrowser = true;
7115            }
7116
7117            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7118            // If there were 'always' entries their preferred order has been set, so we also
7119            // back that off to make the alternatives equivalent
7120            if (alwaysAskList.size() > 0) {
7121                for (ResolveInfo i : result) {
7122                    i.preferredOrder = 0;
7123                }
7124                result.addAll(alwaysAskList);
7125                includeBrowser = true;
7126            }
7127
7128            if (includeBrowser) {
7129                // Also add browsers (all of them or only the default one)
7130                if (DEBUG_DOMAIN_VERIFICATION) {
7131                    Slog.v(TAG, "   ...including browsers in candidate set");
7132                }
7133                if ((matchFlags & MATCH_ALL) != 0) {
7134                    result.addAll(matchAllList);
7135                } else {
7136                    // Browser/generic handling case.  If there's a default browser, go straight
7137                    // to that (but only if there is no other higher-priority match).
7138                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7139                    int maxMatchPrio = 0;
7140                    ResolveInfo defaultBrowserMatch = null;
7141                    final int numCandidates = matchAllList.size();
7142                    for (int n = 0; n < numCandidates; n++) {
7143                        ResolveInfo info = matchAllList.get(n);
7144                        // track the highest overall match priority...
7145                        if (info.priority > maxMatchPrio) {
7146                            maxMatchPrio = info.priority;
7147                        }
7148                        // ...and the highest-priority default browser match
7149                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7150                            if (defaultBrowserMatch == null
7151                                    || (defaultBrowserMatch.priority < info.priority)) {
7152                                if (debug) {
7153                                    Slog.v(TAG, "Considering default browser match " + info);
7154                                }
7155                                defaultBrowserMatch = info;
7156                            }
7157                        }
7158                    }
7159                    if (defaultBrowserMatch != null
7160                            && defaultBrowserMatch.priority >= maxMatchPrio
7161                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7162                    {
7163                        if (debug) {
7164                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7165                        }
7166                        result.add(defaultBrowserMatch);
7167                    } else {
7168                        result.addAll(matchAllList);
7169                    }
7170                }
7171
7172                // If there is nothing selected, add all candidates and remove the ones that the user
7173                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7174                if (result.size() == 0) {
7175                    result.addAll(candidates);
7176                    result.removeAll(neverList);
7177                }
7178            }
7179        }
7180        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7181            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7182                    result.size());
7183            for (ResolveInfo info : result) {
7184                Slog.v(TAG, "  + " + info.activityInfo);
7185            }
7186        }
7187        return result;
7188    }
7189
7190    // Returns a packed value as a long:
7191    //
7192    // high 'int'-sized word: link status: undefined/ask/never/always.
7193    // low 'int'-sized word: relative priority among 'always' results.
7194    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7195        long result = ps.getDomainVerificationStatusForUser(userId);
7196        // if none available, get the master status
7197        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7198            if (ps.getIntentFilterVerificationInfo() != null) {
7199                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7200            }
7201        }
7202        return result;
7203    }
7204
7205    private ResolveInfo querySkipCurrentProfileIntents(
7206            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7207            int flags, int sourceUserId) {
7208        if (matchingFilters != null) {
7209            int size = matchingFilters.size();
7210            for (int i = 0; i < size; i ++) {
7211                CrossProfileIntentFilter filter = matchingFilters.get(i);
7212                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7213                    // Checking if there are activities in the target user that can handle the
7214                    // intent.
7215                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7216                            resolvedType, flags, sourceUserId);
7217                    if (resolveInfo != null) {
7218                        return resolveInfo;
7219                    }
7220                }
7221            }
7222        }
7223        return null;
7224    }
7225
7226    // Return matching ResolveInfo in target user if any.
7227    private ResolveInfo queryCrossProfileIntents(
7228            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7229            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7230        if (matchingFilters != null) {
7231            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7232            // match the same intent. For performance reasons, it is better not to
7233            // run queryIntent twice for the same userId
7234            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7235            int size = matchingFilters.size();
7236            for (int i = 0; i < size; i++) {
7237                CrossProfileIntentFilter filter = matchingFilters.get(i);
7238                int targetUserId = filter.getTargetUserId();
7239                boolean skipCurrentProfile =
7240                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7241                boolean skipCurrentProfileIfNoMatchFound =
7242                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7243                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7244                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7245                    // Checking if there are activities in the target user that can handle the
7246                    // intent.
7247                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7248                            resolvedType, flags, sourceUserId);
7249                    if (resolveInfo != null) return resolveInfo;
7250                    alreadyTriedUserIds.put(targetUserId, true);
7251                }
7252            }
7253        }
7254        return null;
7255    }
7256
7257    /**
7258     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7259     * will forward the intent to the filter's target user.
7260     * Otherwise, returns null.
7261     */
7262    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7263            String resolvedType, int flags, int sourceUserId) {
7264        int targetUserId = filter.getTargetUserId();
7265        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7266                resolvedType, flags, targetUserId);
7267        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7268            // If all the matches in the target profile are suspended, return null.
7269            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7270                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7271                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7272                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7273                            targetUserId);
7274                }
7275            }
7276        }
7277        return null;
7278    }
7279
7280    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7281            int sourceUserId, int targetUserId) {
7282        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7283        long ident = Binder.clearCallingIdentity();
7284        boolean targetIsProfile;
7285        try {
7286            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7287        } finally {
7288            Binder.restoreCallingIdentity(ident);
7289        }
7290        String className;
7291        if (targetIsProfile) {
7292            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7293        } else {
7294            className = FORWARD_INTENT_TO_PARENT;
7295        }
7296        ComponentName forwardingActivityComponentName = new ComponentName(
7297                mAndroidApplication.packageName, className);
7298        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7299                sourceUserId);
7300        if (!targetIsProfile) {
7301            forwardingActivityInfo.showUserIcon = targetUserId;
7302            forwardingResolveInfo.noResourceId = true;
7303        }
7304        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7305        forwardingResolveInfo.priority = 0;
7306        forwardingResolveInfo.preferredOrder = 0;
7307        forwardingResolveInfo.match = 0;
7308        forwardingResolveInfo.isDefault = true;
7309        forwardingResolveInfo.filter = filter;
7310        forwardingResolveInfo.targetUserId = targetUserId;
7311        return forwardingResolveInfo;
7312    }
7313
7314    @Override
7315    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7316            Intent[] specifics, String[] specificTypes, Intent intent,
7317            String resolvedType, int flags, int userId) {
7318        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7319                specificTypes, intent, resolvedType, flags, userId));
7320    }
7321
7322    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7323            Intent[] specifics, String[] specificTypes, Intent intent,
7324            String resolvedType, int flags, int userId) {
7325        if (!sUserManager.exists(userId)) return Collections.emptyList();
7326        final int callingUid = Binder.getCallingUid();
7327        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7328                false /*includeInstantApps*/);
7329        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7330                false /*requireFullPermission*/, false /*checkShell*/,
7331                "query intent activity options");
7332        final String resultsAction = intent.getAction();
7333
7334        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7335                | PackageManager.GET_RESOLVED_FILTER, userId);
7336
7337        if (DEBUG_INTENT_MATCHING) {
7338            Log.v(TAG, "Query " + intent + ": " + results);
7339        }
7340
7341        int specificsPos = 0;
7342        int N;
7343
7344        // todo: note that the algorithm used here is O(N^2).  This
7345        // isn't a problem in our current environment, but if we start running
7346        // into situations where we have more than 5 or 10 matches then this
7347        // should probably be changed to something smarter...
7348
7349        // First we go through and resolve each of the specific items
7350        // that were supplied, taking care of removing any corresponding
7351        // duplicate items in the generic resolve list.
7352        if (specifics != null) {
7353            for (int i=0; i<specifics.length; i++) {
7354                final Intent sintent = specifics[i];
7355                if (sintent == null) {
7356                    continue;
7357                }
7358
7359                if (DEBUG_INTENT_MATCHING) {
7360                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7361                }
7362
7363                String action = sintent.getAction();
7364                if (resultsAction != null && resultsAction.equals(action)) {
7365                    // If this action was explicitly requested, then don't
7366                    // remove things that have it.
7367                    action = null;
7368                }
7369
7370                ResolveInfo ri = null;
7371                ActivityInfo ai = null;
7372
7373                ComponentName comp = sintent.getComponent();
7374                if (comp == null) {
7375                    ri = resolveIntent(
7376                        sintent,
7377                        specificTypes != null ? specificTypes[i] : null,
7378                            flags, userId);
7379                    if (ri == null) {
7380                        continue;
7381                    }
7382                    if (ri == mResolveInfo) {
7383                        // ACK!  Must do something better with this.
7384                    }
7385                    ai = ri.activityInfo;
7386                    comp = new ComponentName(ai.applicationInfo.packageName,
7387                            ai.name);
7388                } else {
7389                    ai = getActivityInfo(comp, flags, userId);
7390                    if (ai == null) {
7391                        continue;
7392                    }
7393                }
7394
7395                // Look for any generic query activities that are duplicates
7396                // of this specific one, and remove them from the results.
7397                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7398                N = results.size();
7399                int j;
7400                for (j=specificsPos; j<N; j++) {
7401                    ResolveInfo sri = results.get(j);
7402                    if ((sri.activityInfo.name.equals(comp.getClassName())
7403                            && sri.activityInfo.applicationInfo.packageName.equals(
7404                                    comp.getPackageName()))
7405                        || (action != null && sri.filter.matchAction(action))) {
7406                        results.remove(j);
7407                        if (DEBUG_INTENT_MATCHING) Log.v(
7408                            TAG, "Removing duplicate item from " + j
7409                            + " due to specific " + specificsPos);
7410                        if (ri == null) {
7411                            ri = sri;
7412                        }
7413                        j--;
7414                        N--;
7415                    }
7416                }
7417
7418                // Add this specific item to its proper place.
7419                if (ri == null) {
7420                    ri = new ResolveInfo();
7421                    ri.activityInfo = ai;
7422                }
7423                results.add(specificsPos, ri);
7424                ri.specificIndex = i;
7425                specificsPos++;
7426            }
7427        }
7428
7429        // Now we go through the remaining generic results and remove any
7430        // duplicate actions that are found here.
7431        N = results.size();
7432        for (int i=specificsPos; i<N-1; i++) {
7433            final ResolveInfo rii = results.get(i);
7434            if (rii.filter == null) {
7435                continue;
7436            }
7437
7438            // Iterate over all of the actions of this result's intent
7439            // filter...  typically this should be just one.
7440            final Iterator<String> it = rii.filter.actionsIterator();
7441            if (it == null) {
7442                continue;
7443            }
7444            while (it.hasNext()) {
7445                final String action = it.next();
7446                if (resultsAction != null && resultsAction.equals(action)) {
7447                    // If this action was explicitly requested, then don't
7448                    // remove things that have it.
7449                    continue;
7450                }
7451                for (int j=i+1; j<N; j++) {
7452                    final ResolveInfo rij = results.get(j);
7453                    if (rij.filter != null && rij.filter.hasAction(action)) {
7454                        results.remove(j);
7455                        if (DEBUG_INTENT_MATCHING) Log.v(
7456                            TAG, "Removing duplicate item from " + j
7457                            + " due to action " + action + " at " + i);
7458                        j--;
7459                        N--;
7460                    }
7461                }
7462            }
7463
7464            // If the caller didn't request filter information, drop it now
7465            // so we don't have to marshall/unmarshall it.
7466            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7467                rii.filter = null;
7468            }
7469        }
7470
7471        // Filter out the caller activity if so requested.
7472        if (caller != null) {
7473            N = results.size();
7474            for (int i=0; i<N; i++) {
7475                ActivityInfo ainfo = results.get(i).activityInfo;
7476                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7477                        && caller.getClassName().equals(ainfo.name)) {
7478                    results.remove(i);
7479                    break;
7480                }
7481            }
7482        }
7483
7484        // If the caller didn't request filter information,
7485        // drop them now so we don't have to
7486        // marshall/unmarshall it.
7487        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7488            N = results.size();
7489            for (int i=0; i<N; i++) {
7490                results.get(i).filter = null;
7491            }
7492        }
7493
7494        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7495        return results;
7496    }
7497
7498    @Override
7499    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7500            String resolvedType, int flags, int userId) {
7501        return new ParceledListSlice<>(
7502                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7503                        false /*allowDynamicSplits*/));
7504    }
7505
7506    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7507            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7508        if (!sUserManager.exists(userId)) return Collections.emptyList();
7509        final int callingUid = Binder.getCallingUid();
7510        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7511                false /*requireFullPermission*/, false /*checkShell*/,
7512                "query intent receivers");
7513        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7514        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7515                false /*includeInstantApps*/);
7516        ComponentName comp = intent.getComponent();
7517        if (comp == null) {
7518            if (intent.getSelector() != null) {
7519                intent = intent.getSelector();
7520                comp = intent.getComponent();
7521            }
7522        }
7523        if (comp != null) {
7524            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7525            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7526            if (ai != null) {
7527                // When specifying an explicit component, we prevent the activity from being
7528                // used when either 1) the calling package is normal and the activity is within
7529                // an instant application or 2) the calling package is ephemeral and the
7530                // activity is not visible to instant applications.
7531                final boolean matchInstantApp =
7532                        (flags & PackageManager.MATCH_INSTANT) != 0;
7533                final boolean matchVisibleToInstantAppOnly =
7534                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7535                final boolean matchExplicitlyVisibleOnly =
7536                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7537                final boolean isCallerInstantApp =
7538                        instantAppPkgName != null;
7539                final boolean isTargetSameInstantApp =
7540                        comp.getPackageName().equals(instantAppPkgName);
7541                final boolean isTargetInstantApp =
7542                        (ai.applicationInfo.privateFlags
7543                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7544                final boolean isTargetVisibleToInstantApp =
7545                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7546                final boolean isTargetExplicitlyVisibleToInstantApp =
7547                        isTargetVisibleToInstantApp
7548                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7549                final boolean isTargetHiddenFromInstantApp =
7550                        !isTargetVisibleToInstantApp
7551                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7552                final boolean blockResolution =
7553                        !isTargetSameInstantApp
7554                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7555                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7556                                        && isTargetHiddenFromInstantApp));
7557                if (!blockResolution) {
7558                    ResolveInfo ri = new ResolveInfo();
7559                    ri.activityInfo = ai;
7560                    list.add(ri);
7561                }
7562            }
7563            return applyPostResolutionFilter(
7564                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7565        }
7566
7567        // reader
7568        synchronized (mPackages) {
7569            String pkgName = intent.getPackage();
7570            if (pkgName == null) {
7571                final List<ResolveInfo> result =
7572                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7573                return applyPostResolutionFilter(
7574                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7575            }
7576            final PackageParser.Package pkg = mPackages.get(pkgName);
7577            if (pkg != null) {
7578                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7579                        intent, resolvedType, flags, pkg.receivers, userId);
7580                return applyPostResolutionFilter(
7581                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7582            }
7583            return Collections.emptyList();
7584        }
7585    }
7586
7587    @Override
7588    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7589        final int callingUid = Binder.getCallingUid();
7590        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7591    }
7592
7593    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7594            int userId, int callingUid) {
7595        if (!sUserManager.exists(userId)) return null;
7596        flags = updateFlagsForResolve(
7597                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7598        List<ResolveInfo> query = queryIntentServicesInternal(
7599                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7600        if (query != null) {
7601            if (query.size() >= 1) {
7602                // If there is more than one service with the same priority,
7603                // just arbitrarily pick the first one.
7604                return query.get(0);
7605            }
7606        }
7607        return null;
7608    }
7609
7610    @Override
7611    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7612            String resolvedType, int flags, int userId) {
7613        final int callingUid = Binder.getCallingUid();
7614        return new ParceledListSlice<>(queryIntentServicesInternal(
7615                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7616    }
7617
7618    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7619            String resolvedType, int flags, int userId, int callingUid,
7620            boolean includeInstantApps) {
7621        if (!sUserManager.exists(userId)) return Collections.emptyList();
7622        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7623                false /*requireFullPermission*/, false /*checkShell*/,
7624                "query intent receivers");
7625        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7626        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7627        ComponentName comp = intent.getComponent();
7628        if (comp == null) {
7629            if (intent.getSelector() != null) {
7630                intent = intent.getSelector();
7631                comp = intent.getComponent();
7632            }
7633        }
7634        if (comp != null) {
7635            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7636            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7637            if (si != null) {
7638                // When specifying an explicit component, we prevent the service from being
7639                // used when either 1) the service is in an instant application and the
7640                // caller is not the same instant application or 2) the calling package is
7641                // ephemeral and the activity is not visible to ephemeral applications.
7642                final boolean matchInstantApp =
7643                        (flags & PackageManager.MATCH_INSTANT) != 0;
7644                final boolean matchVisibleToInstantAppOnly =
7645                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7646                final boolean isCallerInstantApp =
7647                        instantAppPkgName != null;
7648                final boolean isTargetSameInstantApp =
7649                        comp.getPackageName().equals(instantAppPkgName);
7650                final boolean isTargetInstantApp =
7651                        (si.applicationInfo.privateFlags
7652                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7653                final boolean isTargetHiddenFromInstantApp =
7654                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7655                final boolean blockResolution =
7656                        !isTargetSameInstantApp
7657                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7658                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7659                                        && isTargetHiddenFromInstantApp));
7660                if (!blockResolution) {
7661                    final ResolveInfo ri = new ResolveInfo();
7662                    ri.serviceInfo = si;
7663                    list.add(ri);
7664                }
7665            }
7666            return list;
7667        }
7668
7669        // reader
7670        synchronized (mPackages) {
7671            String pkgName = intent.getPackage();
7672            if (pkgName == null) {
7673                return applyPostServiceResolutionFilter(
7674                        mServices.queryIntent(intent, resolvedType, flags, userId),
7675                        instantAppPkgName);
7676            }
7677            final PackageParser.Package pkg = mPackages.get(pkgName);
7678            if (pkg != null) {
7679                return applyPostServiceResolutionFilter(
7680                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7681                                userId),
7682                        instantAppPkgName);
7683            }
7684            return Collections.emptyList();
7685        }
7686    }
7687
7688    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7689            String instantAppPkgName) {
7690        if (instantAppPkgName == null) {
7691            return resolveInfos;
7692        }
7693        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7694            final ResolveInfo info = resolveInfos.get(i);
7695            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7696            // allow services that are defined in the provided package
7697            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7698                if (info.serviceInfo.splitName != null
7699                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7700                                info.serviceInfo.splitName)) {
7701                    // requested service is defined in a split that hasn't been installed yet.
7702                    // add the installer to the resolve list
7703                    if (DEBUG_INSTANT) {
7704                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7705                    }
7706                    final ResolveInfo installerInfo = new ResolveInfo(
7707                            mInstantAppInstallerInfo);
7708                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7709                            null /* installFailureActivity */,
7710                            info.serviceInfo.packageName,
7711                            info.serviceInfo.applicationInfo.longVersionCode,
7712                            info.serviceInfo.splitName);
7713                    // add a non-generic filter
7714                    installerInfo.filter = new IntentFilter();
7715                    // load resources from the correct package
7716                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7717                    resolveInfos.set(i, installerInfo);
7718                }
7719                continue;
7720            }
7721            // allow services that have been explicitly exposed to ephemeral apps
7722            if (!isEphemeralApp
7723                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7724                continue;
7725            }
7726            resolveInfos.remove(i);
7727        }
7728        return resolveInfos;
7729    }
7730
7731    @Override
7732    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7733            String resolvedType, int flags, int userId) {
7734        return new ParceledListSlice<>(
7735                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7736    }
7737
7738    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7739            Intent intent, String resolvedType, int flags, int userId) {
7740        if (!sUserManager.exists(userId)) return Collections.emptyList();
7741        final int callingUid = Binder.getCallingUid();
7742        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7743        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7744                false /*includeInstantApps*/);
7745        ComponentName comp = intent.getComponent();
7746        if (comp == null) {
7747            if (intent.getSelector() != null) {
7748                intent = intent.getSelector();
7749                comp = intent.getComponent();
7750            }
7751        }
7752        if (comp != null) {
7753            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7754            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7755            if (pi != null) {
7756                // When specifying an explicit component, we prevent the provider from being
7757                // used when either 1) the provider is in an instant application and the
7758                // caller is not the same instant application or 2) the calling package is an
7759                // instant application and the provider is not visible to instant applications.
7760                final boolean matchInstantApp =
7761                        (flags & PackageManager.MATCH_INSTANT) != 0;
7762                final boolean matchVisibleToInstantAppOnly =
7763                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7764                final boolean isCallerInstantApp =
7765                        instantAppPkgName != null;
7766                final boolean isTargetSameInstantApp =
7767                        comp.getPackageName().equals(instantAppPkgName);
7768                final boolean isTargetInstantApp =
7769                        (pi.applicationInfo.privateFlags
7770                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7771                final boolean isTargetHiddenFromInstantApp =
7772                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7773                final boolean blockResolution =
7774                        !isTargetSameInstantApp
7775                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7776                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7777                                        && isTargetHiddenFromInstantApp));
7778                if (!blockResolution) {
7779                    final ResolveInfo ri = new ResolveInfo();
7780                    ri.providerInfo = pi;
7781                    list.add(ri);
7782                }
7783            }
7784            return list;
7785        }
7786
7787        // reader
7788        synchronized (mPackages) {
7789            String pkgName = intent.getPackage();
7790            if (pkgName == null) {
7791                return applyPostContentProviderResolutionFilter(
7792                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7793                        instantAppPkgName);
7794            }
7795            final PackageParser.Package pkg = mPackages.get(pkgName);
7796            if (pkg != null) {
7797                return applyPostContentProviderResolutionFilter(
7798                        mProviders.queryIntentForPackage(
7799                        intent, resolvedType, flags, pkg.providers, userId),
7800                        instantAppPkgName);
7801            }
7802            return Collections.emptyList();
7803        }
7804    }
7805
7806    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7807            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7808        if (instantAppPkgName == null) {
7809            return resolveInfos;
7810        }
7811        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7812            final ResolveInfo info = resolveInfos.get(i);
7813            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7814            // allow providers that are defined in the provided package
7815            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7816                if (info.providerInfo.splitName != null
7817                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7818                                info.providerInfo.splitName)) {
7819                    // requested provider is defined in a split that hasn't been installed yet.
7820                    // add the installer to the resolve list
7821                    if (DEBUG_INSTANT) {
7822                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7823                    }
7824                    final ResolveInfo installerInfo = new ResolveInfo(
7825                            mInstantAppInstallerInfo);
7826                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7827                            null /*failureActivity*/,
7828                            info.providerInfo.packageName,
7829                            info.providerInfo.applicationInfo.longVersionCode,
7830                            info.providerInfo.splitName);
7831                    // add a non-generic filter
7832                    installerInfo.filter = new IntentFilter();
7833                    // load resources from the correct package
7834                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7835                    resolveInfos.set(i, installerInfo);
7836                }
7837                continue;
7838            }
7839            // allow providers that have been explicitly exposed to instant applications
7840            if (!isEphemeralApp
7841                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7842                continue;
7843            }
7844            resolveInfos.remove(i);
7845        }
7846        return resolveInfos;
7847    }
7848
7849    @Override
7850    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7851        final int callingUid = Binder.getCallingUid();
7852        if (getInstantAppPackageName(callingUid) != null) {
7853            return ParceledListSlice.emptyList();
7854        }
7855        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7856        flags = updateFlagsForPackage(flags, userId, null);
7857        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7858        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7859                true /* requireFullPermission */, false /* checkShell */,
7860                "get installed packages");
7861
7862        // writer
7863        synchronized (mPackages) {
7864            ArrayList<PackageInfo> list;
7865            if (listUninstalled) {
7866                list = new ArrayList<>(mSettings.mPackages.size());
7867                for (PackageSetting ps : mSettings.mPackages.values()) {
7868                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7869                        continue;
7870                    }
7871                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7872                        continue;
7873                    }
7874                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7875                    if (pi != null) {
7876                        list.add(pi);
7877                    }
7878                }
7879            } else {
7880                list = new ArrayList<>(mPackages.size());
7881                for (PackageParser.Package p : mPackages.values()) {
7882                    final PackageSetting ps = (PackageSetting) p.mExtras;
7883                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7884                        continue;
7885                    }
7886                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7887                        continue;
7888                    }
7889                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7890                            p.mExtras, flags, userId);
7891                    if (pi != null) {
7892                        list.add(pi);
7893                    }
7894                }
7895            }
7896
7897            return new ParceledListSlice<>(list);
7898        }
7899    }
7900
7901    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7902            String[] permissions, boolean[] tmp, int flags, int userId) {
7903        int numMatch = 0;
7904        final PermissionsState permissionsState = ps.getPermissionsState();
7905        for (int i=0; i<permissions.length; i++) {
7906            final String permission = permissions[i];
7907            if (permissionsState.hasPermission(permission, userId)) {
7908                tmp[i] = true;
7909                numMatch++;
7910            } else {
7911                tmp[i] = false;
7912            }
7913        }
7914        if (numMatch == 0) {
7915            return;
7916        }
7917        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7918
7919        // The above might return null in cases of uninstalled apps or install-state
7920        // skew across users/profiles.
7921        if (pi != null) {
7922            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7923                if (numMatch == permissions.length) {
7924                    pi.requestedPermissions = permissions;
7925                } else {
7926                    pi.requestedPermissions = new String[numMatch];
7927                    numMatch = 0;
7928                    for (int i=0; i<permissions.length; i++) {
7929                        if (tmp[i]) {
7930                            pi.requestedPermissions[numMatch] = permissions[i];
7931                            numMatch++;
7932                        }
7933                    }
7934                }
7935            }
7936            list.add(pi);
7937        }
7938    }
7939
7940    @Override
7941    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7942            String[] permissions, int flags, int userId) {
7943        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7944        flags = updateFlagsForPackage(flags, userId, permissions);
7945        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7946                true /* requireFullPermission */, false /* checkShell */,
7947                "get packages holding permissions");
7948        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7949
7950        // writer
7951        synchronized (mPackages) {
7952            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7953            boolean[] tmpBools = new boolean[permissions.length];
7954            if (listUninstalled) {
7955                for (PackageSetting ps : mSettings.mPackages.values()) {
7956                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7957                            userId);
7958                }
7959            } else {
7960                for (PackageParser.Package pkg : mPackages.values()) {
7961                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7962                    if (ps != null) {
7963                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7964                                userId);
7965                    }
7966                }
7967            }
7968
7969            return new ParceledListSlice<PackageInfo>(list);
7970        }
7971    }
7972
7973    @Override
7974    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7975        final int callingUid = Binder.getCallingUid();
7976        if (getInstantAppPackageName(callingUid) != null) {
7977            return ParceledListSlice.emptyList();
7978        }
7979        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7980        flags = updateFlagsForApplication(flags, userId, null);
7981        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7982
7983        // writer
7984        synchronized (mPackages) {
7985            ArrayList<ApplicationInfo> list;
7986            if (listUninstalled) {
7987                list = new ArrayList<>(mSettings.mPackages.size());
7988                for (PackageSetting ps : mSettings.mPackages.values()) {
7989                    ApplicationInfo ai;
7990                    int effectiveFlags = flags;
7991                    if (ps.isSystem()) {
7992                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7993                    }
7994                    if (ps.pkg != null) {
7995                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7996                            continue;
7997                        }
7998                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7999                            continue;
8000                        }
8001                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8002                                ps.readUserState(userId), userId);
8003                        if (ai != null) {
8004                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8005                        }
8006                    } else {
8007                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8008                        // and already converts to externally visible package name
8009                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8010                                callingUid, effectiveFlags, userId);
8011                    }
8012                    if (ai != null) {
8013                        list.add(ai);
8014                    }
8015                }
8016            } else {
8017                list = new ArrayList<>(mPackages.size());
8018                for (PackageParser.Package p : mPackages.values()) {
8019                    if (p.mExtras != null) {
8020                        PackageSetting ps = (PackageSetting) p.mExtras;
8021                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8022                            continue;
8023                        }
8024                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8025                            continue;
8026                        }
8027                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8028                                ps.readUserState(userId), userId);
8029                        if (ai != null) {
8030                            ai.packageName = resolveExternalPackageNameLPr(p);
8031                            list.add(ai);
8032                        }
8033                    }
8034                }
8035            }
8036
8037            return new ParceledListSlice<>(list);
8038        }
8039    }
8040
8041    @Override
8042    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8043        if (HIDE_EPHEMERAL_APIS) {
8044            return null;
8045        }
8046        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8047            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8048                    "getEphemeralApplications");
8049        }
8050        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8051                true /* requireFullPermission */, false /* checkShell */,
8052                "getEphemeralApplications");
8053        synchronized (mPackages) {
8054            List<InstantAppInfo> instantApps = mInstantAppRegistry
8055                    .getInstantAppsLPr(userId);
8056            if (instantApps != null) {
8057                return new ParceledListSlice<>(instantApps);
8058            }
8059        }
8060        return null;
8061    }
8062
8063    @Override
8064    public boolean isInstantApp(String packageName, int userId) {
8065        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8066                true /* requireFullPermission */, false /* checkShell */,
8067                "isInstantApp");
8068        if (HIDE_EPHEMERAL_APIS) {
8069            return false;
8070        }
8071
8072        synchronized (mPackages) {
8073            int callingUid = Binder.getCallingUid();
8074            if (Process.isIsolated(callingUid)) {
8075                callingUid = mIsolatedOwners.get(callingUid);
8076            }
8077            final PackageSetting ps = mSettings.mPackages.get(packageName);
8078            PackageParser.Package pkg = mPackages.get(packageName);
8079            final boolean returnAllowed =
8080                    ps != null
8081                    && (isCallerSameApp(packageName, callingUid)
8082                            || canViewInstantApps(callingUid, userId)
8083                            || mInstantAppRegistry.isInstantAccessGranted(
8084                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8085            if (returnAllowed) {
8086                return ps.getInstantApp(userId);
8087            }
8088        }
8089        return false;
8090    }
8091
8092    @Override
8093    public byte[] getInstantAppCookie(String packageName, int userId) {
8094        if (HIDE_EPHEMERAL_APIS) {
8095            return null;
8096        }
8097
8098        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8099                true /* requireFullPermission */, false /* checkShell */,
8100                "getInstantAppCookie");
8101        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8102            return null;
8103        }
8104        synchronized (mPackages) {
8105            return mInstantAppRegistry.getInstantAppCookieLPw(
8106                    packageName, userId);
8107        }
8108    }
8109
8110    @Override
8111    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8112        if (HIDE_EPHEMERAL_APIS) {
8113            return true;
8114        }
8115
8116        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8117                true /* requireFullPermission */, true /* checkShell */,
8118                "setInstantAppCookie");
8119        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8120            return false;
8121        }
8122        synchronized (mPackages) {
8123            return mInstantAppRegistry.setInstantAppCookieLPw(
8124                    packageName, cookie, userId);
8125        }
8126    }
8127
8128    @Override
8129    public Bitmap getInstantAppIcon(String packageName, int userId) {
8130        if (HIDE_EPHEMERAL_APIS) {
8131            return null;
8132        }
8133
8134        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8135            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8136                    "getInstantAppIcon");
8137        }
8138        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8139                true /* requireFullPermission */, false /* checkShell */,
8140                "getInstantAppIcon");
8141
8142        synchronized (mPackages) {
8143            return mInstantAppRegistry.getInstantAppIconLPw(
8144                    packageName, userId);
8145        }
8146    }
8147
8148    private boolean isCallerSameApp(String packageName, int uid) {
8149        PackageParser.Package pkg = mPackages.get(packageName);
8150        return pkg != null
8151                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8152    }
8153
8154    @Override
8155    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8156        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8157            return ParceledListSlice.emptyList();
8158        }
8159        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8160    }
8161
8162    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8163        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8164
8165        // reader
8166        synchronized (mPackages) {
8167            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8168            final int userId = UserHandle.getCallingUserId();
8169            while (i.hasNext()) {
8170                final PackageParser.Package p = i.next();
8171                if (p.applicationInfo == null) continue;
8172
8173                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8174                        && !p.applicationInfo.isDirectBootAware();
8175                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8176                        && p.applicationInfo.isDirectBootAware();
8177
8178                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8179                        && (!mSafeMode || isSystemApp(p))
8180                        && (matchesUnaware || matchesAware)) {
8181                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8182                    if (ps != null) {
8183                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8184                                ps.readUserState(userId), userId);
8185                        if (ai != null) {
8186                            finalList.add(ai);
8187                        }
8188                    }
8189                }
8190            }
8191        }
8192
8193        return finalList;
8194    }
8195
8196    @Override
8197    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8198        return resolveContentProviderInternal(name, flags, userId);
8199    }
8200
8201    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8202        if (!sUserManager.exists(userId)) return null;
8203        flags = updateFlagsForComponent(flags, userId, name);
8204        final int callingUid = Binder.getCallingUid();
8205        synchronized (mPackages) {
8206            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8207            PackageSetting ps = provider != null
8208                    ? mSettings.mPackages.get(provider.owner.packageName)
8209                    : null;
8210            if (ps != null) {
8211                // provider not enabled
8212                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8213                    return null;
8214                }
8215                final ComponentName component =
8216                        new ComponentName(provider.info.packageName, provider.info.name);
8217                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8218                    return null;
8219                }
8220                return PackageParser.generateProviderInfo(
8221                        provider, flags, ps.readUserState(userId), userId);
8222            }
8223            return null;
8224        }
8225    }
8226
8227    /**
8228     * @deprecated
8229     */
8230    @Deprecated
8231    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8232        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8233            return;
8234        }
8235        // reader
8236        synchronized (mPackages) {
8237            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8238                    .entrySet().iterator();
8239            final int userId = UserHandle.getCallingUserId();
8240            while (i.hasNext()) {
8241                Map.Entry<String, PackageParser.Provider> entry = i.next();
8242                PackageParser.Provider p = entry.getValue();
8243                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8244
8245                if (ps != null && p.syncable
8246                        && (!mSafeMode || (p.info.applicationInfo.flags
8247                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8248                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8249                            ps.readUserState(userId), userId);
8250                    if (info != null) {
8251                        outNames.add(entry.getKey());
8252                        outInfo.add(info);
8253                    }
8254                }
8255            }
8256        }
8257    }
8258
8259    @Override
8260    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8261            int uid, int flags, String metaDataKey) {
8262        final int callingUid = Binder.getCallingUid();
8263        final int userId = processName != null ? UserHandle.getUserId(uid)
8264                : UserHandle.getCallingUserId();
8265        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8266        flags = updateFlagsForComponent(flags, userId, processName);
8267        ArrayList<ProviderInfo> finalList = null;
8268        // reader
8269        synchronized (mPackages) {
8270            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8271            while (i.hasNext()) {
8272                final PackageParser.Provider p = i.next();
8273                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8274                if (ps != null && p.info.authority != null
8275                        && (processName == null
8276                                || (p.info.processName.equals(processName)
8277                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8278                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8279
8280                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8281                    // parameter.
8282                    if (metaDataKey != null
8283                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8284                        continue;
8285                    }
8286                    final ComponentName component =
8287                            new ComponentName(p.info.packageName, p.info.name);
8288                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8289                        continue;
8290                    }
8291                    if (finalList == null) {
8292                        finalList = new ArrayList<ProviderInfo>(3);
8293                    }
8294                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8295                            ps.readUserState(userId), userId);
8296                    if (info != null) {
8297                        finalList.add(info);
8298                    }
8299                }
8300            }
8301        }
8302
8303        if (finalList != null) {
8304            Collections.sort(finalList, mProviderInitOrderSorter);
8305            return new ParceledListSlice<ProviderInfo>(finalList);
8306        }
8307
8308        return ParceledListSlice.emptyList();
8309    }
8310
8311    @Override
8312    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8313        // reader
8314        synchronized (mPackages) {
8315            final int callingUid = Binder.getCallingUid();
8316            final int callingUserId = UserHandle.getUserId(callingUid);
8317            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8318            if (ps == null) return null;
8319            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8320                return null;
8321            }
8322            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8323            return PackageParser.generateInstrumentationInfo(i, flags);
8324        }
8325    }
8326
8327    @Override
8328    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8329            String targetPackage, int flags) {
8330        final int callingUid = Binder.getCallingUid();
8331        final int callingUserId = UserHandle.getUserId(callingUid);
8332        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8333        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8334            return ParceledListSlice.emptyList();
8335        }
8336        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8337    }
8338
8339    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8340            int flags) {
8341        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8342
8343        // reader
8344        synchronized (mPackages) {
8345            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8346            while (i.hasNext()) {
8347                final PackageParser.Instrumentation p = i.next();
8348                if (targetPackage == null
8349                        || targetPackage.equals(p.info.targetPackage)) {
8350                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8351                            flags);
8352                    if (ii != null) {
8353                        finalList.add(ii);
8354                    }
8355                }
8356            }
8357        }
8358
8359        return finalList;
8360    }
8361
8362    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8363        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8364        try {
8365            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8366        } finally {
8367            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8368        }
8369    }
8370
8371    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8372        final File[] files = scanDir.listFiles();
8373        if (ArrayUtils.isEmpty(files)) {
8374            Log.d(TAG, "No files in app dir " + scanDir);
8375            return;
8376        }
8377
8378        if (DEBUG_PACKAGE_SCANNING) {
8379            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8380                    + " flags=0x" + Integer.toHexString(parseFlags));
8381        }
8382        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8383                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8384                mParallelPackageParserCallback)) {
8385            // Submit files for parsing in parallel
8386            int fileCount = 0;
8387            for (File file : files) {
8388                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8389                        && !PackageInstallerService.isStageName(file.getName());
8390                if (!isPackage) {
8391                    // Ignore entries which are not packages
8392                    continue;
8393                }
8394                parallelPackageParser.submit(file, parseFlags);
8395                fileCount++;
8396            }
8397
8398            // Process results one by one
8399            for (; fileCount > 0; fileCount--) {
8400                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8401                Throwable throwable = parseResult.throwable;
8402                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8403
8404                if (throwable == null) {
8405                    // TODO(toddke): move lower in the scan chain
8406                    // Static shared libraries have synthetic package names
8407                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8408                        renameStaticSharedLibraryPackage(parseResult.pkg);
8409                    }
8410                    try {
8411                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8412                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8413                                    currentTime, null);
8414                        }
8415                    } catch (PackageManagerException e) {
8416                        errorCode = e.error;
8417                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8418                    }
8419                } else if (throwable instanceof PackageParser.PackageParserException) {
8420                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8421                            throwable;
8422                    errorCode = e.error;
8423                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8424                } else {
8425                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8426                            + parseResult.scanFile, throwable);
8427                }
8428
8429                // Delete invalid userdata apps
8430                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8431                        errorCode != PackageManager.INSTALL_SUCCEEDED) {
8432                    logCriticalInfo(Log.WARN,
8433                            "Deleting invalid package at " + parseResult.scanFile);
8434                    removeCodePathLI(parseResult.scanFile);
8435                }
8436            }
8437        }
8438    }
8439
8440    public static void reportSettingsProblem(int priority, String msg) {
8441        logCriticalInfo(priority, msg);
8442    }
8443
8444    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8445            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8446        // When upgrading from pre-N MR1, verify the package time stamp using the package
8447        // directory and not the APK file.
8448        final long lastModifiedTime = mIsPreNMR1Upgrade
8449                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8450        if (ps != null && !forceCollect
8451                && ps.codePathString.equals(pkg.codePath)
8452                && ps.timeStamp == lastModifiedTime
8453                && !isCompatSignatureUpdateNeeded(pkg)
8454                && !isRecoverSignatureUpdateNeeded(pkg)) {
8455            if (ps.signatures.mSigningDetails.signatures != null
8456                    && ps.signatures.mSigningDetails.signatures.length != 0
8457                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8458                            != SignatureSchemeVersion.UNKNOWN) {
8459                // Optimization: reuse the existing cached signing data
8460                // if the package appears to be unchanged.
8461                pkg.mSigningDetails =
8462                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8463                return;
8464            }
8465
8466            Slog.w(TAG, "PackageSetting for " + ps.name
8467                    + " is missing signatures.  Collecting certs again to recover them.");
8468        } else {
8469            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8470                    (forceCollect ? " (forced)" : ""));
8471        }
8472
8473        try {
8474            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8475            PackageParser.collectCertificates(pkg, skipVerify);
8476        } catch (PackageParserException e) {
8477            throw PackageManagerException.from(e);
8478        } finally {
8479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8480        }
8481    }
8482
8483    /**
8484     *  Traces a package scan.
8485     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8486     */
8487    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8488            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8489        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8490        try {
8491            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8492        } finally {
8493            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8494        }
8495    }
8496
8497    /**
8498     *  Scans a package and returns the newly parsed package.
8499     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8500     */
8501    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8502            long currentTime, UserHandle user) throws PackageManagerException {
8503        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8504        PackageParser pp = new PackageParser();
8505        pp.setSeparateProcesses(mSeparateProcesses);
8506        pp.setOnlyCoreApps(mOnlyCore);
8507        pp.setDisplayMetrics(mMetrics);
8508        pp.setCallback(mPackageParserCallback);
8509
8510        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8511        final PackageParser.Package pkg;
8512        try {
8513            pkg = pp.parsePackage(scanFile, parseFlags);
8514        } catch (PackageParserException e) {
8515            throw PackageManagerException.from(e);
8516        } finally {
8517            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8518        }
8519
8520        // Static shared libraries have synthetic package names
8521        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8522            renameStaticSharedLibraryPackage(pkg);
8523        }
8524
8525        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8526    }
8527
8528    /**
8529     *  Scans a package and returns the newly parsed package.
8530     *  @throws PackageManagerException on a parse error.
8531     */
8532    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8533            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8534            @Nullable UserHandle user)
8535                    throws PackageManagerException {
8536        // If the package has children and this is the first dive in the function
8537        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8538        // packages (parent and children) would be successfully scanned before the
8539        // actual scan since scanning mutates internal state and we want to atomically
8540        // install the package and its children.
8541        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8542            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8543                scanFlags |= SCAN_CHECK_ONLY;
8544            }
8545        } else {
8546            scanFlags &= ~SCAN_CHECK_ONLY;
8547        }
8548
8549        // Scan the parent
8550        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8551                scanFlags, currentTime, user);
8552
8553        // Scan the children
8554        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8555        for (int i = 0; i < childCount; i++) {
8556            PackageParser.Package childPackage = pkg.childPackages.get(i);
8557            addForInitLI(childPackage, parseFlags, scanFlags,
8558                    currentTime, user);
8559        }
8560
8561
8562        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8563            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8564        }
8565
8566        return scannedPkg;
8567    }
8568
8569    /**
8570     * Returns if full apk verification can be skipped for the whole package, including the splits.
8571     */
8572    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8573        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8574            return false;
8575        }
8576        // TODO: Allow base and splits to be verified individually.
8577        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8578            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8579                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8580                    return false;
8581                }
8582            }
8583        }
8584        return true;
8585    }
8586
8587    /**
8588     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8589     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8590     * match one in a trusted source, and should be done separately.
8591     */
8592    private boolean canSkipFullApkVerification(String apkPath) {
8593        byte[] rootHashObserved = null;
8594        try {
8595            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8596            if (rootHashObserved == null) {
8597                return false;  // APK does not contain Merkle tree root hash.
8598            }
8599            synchronized (mInstallLock) {
8600                // Returns whether the observed root hash matches what kernel has.
8601                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8602                return true;
8603            }
8604        } catch (InstallerException | IOException | DigestException |
8605                NoSuchAlgorithmException e) {
8606            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8607        }
8608        return false;
8609    }
8610
8611    /**
8612     * Adds a new package to the internal data structures during platform initialization.
8613     * <p>After adding, the package is known to the system and available for querying.
8614     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8615     * etc...], additional checks are performed. Basic verification [such as ensuring
8616     * matching signatures, checking version codes, etc...] occurs if the package is
8617     * identical to a previously known package. If the package fails a signature check,
8618     * the version installed on /data will be removed. If the version of the new package
8619     * is less than or equal than the version on /data, it will be ignored.
8620     * <p>Regardless of the package location, the results are applied to the internal
8621     * structures and the package is made available to the rest of the system.
8622     * <p>NOTE: The return value should be removed. It's the passed in package object.
8623     */
8624    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8625            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8626            @Nullable UserHandle user)
8627                    throws PackageManagerException {
8628        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8629        final String renamedPkgName;
8630        final PackageSetting disabledPkgSetting;
8631        final boolean isSystemPkgUpdated;
8632        final boolean pkgAlreadyExists;
8633        PackageSetting pkgSetting;
8634
8635        // NOTE: installPackageLI() has the same code to setup the package's
8636        // application info. This probably should be done lower in the call
8637        // stack [such as scanPackageOnly()]. However, we verify the application
8638        // info prior to that [in scanPackageNew()] and thus have to setup
8639        // the application info early.
8640        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8641        pkg.setApplicationInfoCodePath(pkg.codePath);
8642        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8643        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8644        pkg.setApplicationInfoResourcePath(pkg.codePath);
8645        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8646        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8647
8648        synchronized (mPackages) {
8649            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8650            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8651            if (realPkgName != null) {
8652                ensurePackageRenamed(pkg, renamedPkgName);
8653            }
8654            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8655            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8656            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8657            pkgAlreadyExists = pkgSetting != null;
8658            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8659            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8660            isSystemPkgUpdated = disabledPkgSetting != null;
8661
8662            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8663                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8664            }
8665
8666            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8667                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8668                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8669                    : null;
8670            if (DEBUG_PACKAGE_SCANNING
8671                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8672                    && sharedUserSetting != null) {
8673                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8674                        + " (uid=" + sharedUserSetting.userId + "):"
8675                        + " packages=" + sharedUserSetting.packages);
8676            }
8677
8678            if (scanSystemPartition) {
8679                // Potentially prune child packages. If the application on the /system
8680                // partition has been updated via OTA, but, is still disabled by a
8681                // version on /data, cycle through all of its children packages and
8682                // remove children that are no longer defined.
8683                if (isSystemPkgUpdated) {
8684                    final int scannedChildCount = (pkg.childPackages != null)
8685                            ? pkg.childPackages.size() : 0;
8686                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8687                            ? disabledPkgSetting.childPackageNames.size() : 0;
8688                    for (int i = 0; i < disabledChildCount; i++) {
8689                        String disabledChildPackageName =
8690                                disabledPkgSetting.childPackageNames.get(i);
8691                        boolean disabledPackageAvailable = false;
8692                        for (int j = 0; j < scannedChildCount; j++) {
8693                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8694                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8695                                disabledPackageAvailable = true;
8696                                break;
8697                            }
8698                        }
8699                        if (!disabledPackageAvailable) {
8700                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8701                        }
8702                    }
8703                    // we're updating the disabled package, so, scan it as the package setting
8704                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
8705                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8706                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8707                            (pkg == mPlatformPackage), user);
8708                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8709                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8710                }
8711            }
8712        }
8713
8714        final boolean newPkgChangedPaths =
8715                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8716        final boolean newPkgVersionGreater =
8717                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8718        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8719                && newPkgChangedPaths && newPkgVersionGreater;
8720        if (isSystemPkgBetter) {
8721            // The version of the application on /system is greater than the version on
8722            // /data. Switch back to the application on /system.
8723            // It's safe to assume the application on /system will correctly scan. If not,
8724            // there won't be a working copy of the application.
8725            synchronized (mPackages) {
8726                // just remove the loaded entries from package lists
8727                mPackages.remove(pkgSetting.name);
8728            }
8729
8730            logCriticalInfo(Log.WARN,
8731                    "System package updated;"
8732                    + " name: " + pkgSetting.name
8733                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8734                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8735
8736            final InstallArgs args = createInstallArgsForExisting(
8737                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8738                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8739            args.cleanUpResourcesLI();
8740            synchronized (mPackages) {
8741                mSettings.enableSystemPackageLPw(pkgSetting.name);
8742            }
8743        }
8744
8745        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8746            // The version of the application on the /system partition is less than or
8747            // equal to the version on the /data partition. Throw an exception and use
8748            // the application already installed on the /data partition.
8749            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8750                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8751                    + " better than this " + pkg.getLongVersionCode());
8752        }
8753
8754        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8755        // force re-collecting certificate.
8756        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8757                disabledPkgSetting);
8758        // Full APK verification can be skipped during certificate collection, only if the file is
8759        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8760        // cases, only data in Signing Block is verified instead of the whole file.
8761        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8762                (forceCollect && canSkipFullPackageVerification(pkg));
8763        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8764
8765        boolean shouldHideSystemApp = false;
8766        // A new application appeared on /system, but, we already have a copy of
8767        // the application installed on /data.
8768        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8769                && !pkgSetting.isSystem()) {
8770
8771            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8772                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8773                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8774                                    pkg.mSigningDetails,
8775                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8776                logCriticalInfo(Log.WARN,
8777                        "System package signature mismatch;"
8778                        + " name: " + pkgSetting.name);
8779                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8780                        "scanPackageInternalLI")) {
8781                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8782                }
8783                pkgSetting = null;
8784            } else if (newPkgVersionGreater) {
8785                // The application on /system is newer than the application on /data.
8786                // Simply remove the application on /data [keeping application data]
8787                // and replace it with the version on /system.
8788                logCriticalInfo(Log.WARN,
8789                        "System package enabled;"
8790                        + " name: " + pkgSetting.name
8791                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8792                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8793                InstallArgs args = createInstallArgsForExisting(
8794                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8795                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8796                synchronized (mInstallLock) {
8797                    args.cleanUpResourcesLI();
8798                }
8799            } else {
8800                // The application on /system is older than the application on /data. Hide
8801                // the application on /system and the version on /data will be scanned later
8802                // and re-added like an update.
8803                shouldHideSystemApp = true;
8804                logCriticalInfo(Log.INFO,
8805                        "System package disabled;"
8806                        + " name: " + pkgSetting.name
8807                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8808                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8809            }
8810        }
8811
8812        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8813                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8814
8815        if (shouldHideSystemApp) {
8816            synchronized (mPackages) {
8817                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8818            }
8819        }
8820        return scannedPkg;
8821    }
8822
8823    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8824        // Derive the new package synthetic package name
8825        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8826                + pkg.staticSharedLibVersion);
8827    }
8828
8829    private static String fixProcessName(String defProcessName,
8830            String processName) {
8831        if (processName == null) {
8832            return defProcessName;
8833        }
8834        return processName;
8835    }
8836
8837    /**
8838     * Enforces that only the system UID or root's UID can call a method exposed
8839     * via Binder.
8840     *
8841     * @param message used as message if SecurityException is thrown
8842     * @throws SecurityException if the caller is not system or root
8843     */
8844    private static final void enforceSystemOrRoot(String message) {
8845        final int uid = Binder.getCallingUid();
8846        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8847            throw new SecurityException(message);
8848        }
8849    }
8850
8851    @Override
8852    public void performFstrimIfNeeded() {
8853        enforceSystemOrRoot("Only the system can request fstrim");
8854
8855        // Before everything else, see whether we need to fstrim.
8856        try {
8857            IStorageManager sm = PackageHelper.getStorageManager();
8858            if (sm != null) {
8859                boolean doTrim = false;
8860                final long interval = android.provider.Settings.Global.getLong(
8861                        mContext.getContentResolver(),
8862                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8863                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8864                if (interval > 0) {
8865                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8866                    if (timeSinceLast > interval) {
8867                        doTrim = true;
8868                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8869                                + "; running immediately");
8870                    }
8871                }
8872                if (doTrim) {
8873                    final boolean dexOptDialogShown;
8874                    synchronized (mPackages) {
8875                        dexOptDialogShown = mDexOptDialogShown;
8876                    }
8877                    if (!isFirstBoot() && dexOptDialogShown) {
8878                        try {
8879                            ActivityManager.getService().showBootMessage(
8880                                    mContext.getResources().getString(
8881                                            R.string.android_upgrading_fstrim), true);
8882                        } catch (RemoteException e) {
8883                        }
8884                    }
8885                    sm.runMaintenance();
8886                }
8887            } else {
8888                Slog.e(TAG, "storageManager service unavailable!");
8889            }
8890        } catch (RemoteException e) {
8891            // Can't happen; StorageManagerService is local
8892        }
8893    }
8894
8895    @Override
8896    public void updatePackagesIfNeeded() {
8897        enforceSystemOrRoot("Only the system can request package update");
8898
8899        // We need to re-extract after an OTA.
8900        boolean causeUpgrade = isUpgrade();
8901
8902        // First boot or factory reset.
8903        // Note: we also handle devices that are upgrading to N right now as if it is their
8904        //       first boot, as they do not have profile data.
8905        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8906
8907        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8908        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8909
8910        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8911            return;
8912        }
8913
8914        List<PackageParser.Package> pkgs;
8915        synchronized (mPackages) {
8916            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8917        }
8918
8919        final long startTime = System.nanoTime();
8920        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8921                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8922                    false /* bootComplete */);
8923
8924        final int elapsedTimeSeconds =
8925                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8926
8927        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8928        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8929        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8930        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8931        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8932    }
8933
8934    /*
8935     * Return the prebuilt profile path given a package base code path.
8936     */
8937    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8938        return pkg.baseCodePath + ".prof";
8939    }
8940
8941    /**
8942     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8943     * containing statistics about the invocation. The array consists of three elements,
8944     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8945     * and {@code numberOfPackagesFailed}.
8946     */
8947    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8948            final int compilationReason, boolean bootComplete) {
8949
8950        int numberOfPackagesVisited = 0;
8951        int numberOfPackagesOptimized = 0;
8952        int numberOfPackagesSkipped = 0;
8953        int numberOfPackagesFailed = 0;
8954        final int numberOfPackagesToDexopt = pkgs.size();
8955
8956        for (PackageParser.Package pkg : pkgs) {
8957            numberOfPackagesVisited++;
8958
8959            boolean useProfileForDexopt = false;
8960
8961            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8962                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8963                // that are already compiled.
8964                File profileFile = new File(getPrebuildProfilePath(pkg));
8965                // Copy profile if it exists.
8966                if (profileFile.exists()) {
8967                    try {
8968                        // We could also do this lazily before calling dexopt in
8969                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8970                        // is that we don't have a good way to say "do this only once".
8971                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8972                                pkg.applicationInfo.uid, pkg.packageName,
8973                                ArtManager.getProfileName(null))) {
8974                            Log.e(TAG, "Installer failed to copy system profile!");
8975                        } else {
8976                            // Disabled as this causes speed-profile compilation during first boot
8977                            // even if things are already compiled.
8978                            // useProfileForDexopt = true;
8979                        }
8980                    } catch (Exception e) {
8981                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8982                                e);
8983                    }
8984                } else {
8985                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8986                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8987                    // minimize the number off apps being speed-profile compiled during first boot.
8988                    // The other paths will not change the filter.
8989                    if (disabledPs != null && disabledPs.pkg.isStub) {
8990                        // The package is the stub one, remove the stub suffix to get the normal
8991                        // package and APK names.
8992                        String systemProfilePath =
8993                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8994                        profileFile = new File(systemProfilePath);
8995                        // If we have a profile for a compressed APK, copy it to the reference
8996                        // location.
8997                        // Note that copying the profile here will cause it to override the
8998                        // reference profile every OTA even though the existing reference profile
8999                        // may have more data. We can't copy during decompression since the
9000                        // directories are not set up at that point.
9001                        if (profileFile.exists()) {
9002                            try {
9003                                // We could also do this lazily before calling dexopt in
9004                                // PackageDexOptimizer to prevent this happening on first boot. The
9005                                // issue is that we don't have a good way to say "do this only
9006                                // once".
9007                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9008                                        pkg.applicationInfo.uid, pkg.packageName,
9009                                        ArtManager.getProfileName(null))) {
9010                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9011                                } else {
9012                                    useProfileForDexopt = true;
9013                                }
9014                            } catch (Exception e) {
9015                                Log.e(TAG, "Failed to copy profile " +
9016                                        profileFile.getAbsolutePath() + " ", e);
9017                            }
9018                        }
9019                    }
9020                }
9021            }
9022
9023            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9024                if (DEBUG_DEXOPT) {
9025                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9026                }
9027                numberOfPackagesSkipped++;
9028                continue;
9029            }
9030
9031            if (DEBUG_DEXOPT) {
9032                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9033                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9034            }
9035
9036            if (showDialog) {
9037                try {
9038                    ActivityManager.getService().showBootMessage(
9039                            mContext.getResources().getString(R.string.android_upgrading_apk,
9040                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9041                } catch (RemoteException e) {
9042                }
9043                synchronized (mPackages) {
9044                    mDexOptDialogShown = true;
9045                }
9046            }
9047
9048            int pkgCompilationReason = compilationReason;
9049            if (useProfileForDexopt) {
9050                // Use background dexopt mode to try and use the profile. Note that this does not
9051                // guarantee usage of the profile.
9052                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9053            }
9054
9055            // checkProfiles is false to avoid merging profiles during boot which
9056            // might interfere with background compilation (b/28612421).
9057            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9058            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9059            // trade-off worth doing to save boot time work.
9060            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9061            if (compilationReason == REASON_FIRST_BOOT) {
9062                // TODO: This doesn't cover the upgrade case, we should check for this too.
9063                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9064            }
9065            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9066                    pkg.packageName,
9067                    pkgCompilationReason,
9068                    dexoptFlags));
9069
9070            switch (primaryDexOptStaus) {
9071                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9072                    numberOfPackagesOptimized++;
9073                    break;
9074                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9075                    numberOfPackagesSkipped++;
9076                    break;
9077                case PackageDexOptimizer.DEX_OPT_FAILED:
9078                    numberOfPackagesFailed++;
9079                    break;
9080                default:
9081                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9082                    break;
9083            }
9084        }
9085
9086        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9087                numberOfPackagesFailed };
9088    }
9089
9090    @Override
9091    public void notifyPackageUse(String packageName, int reason) {
9092        synchronized (mPackages) {
9093            final int callingUid = Binder.getCallingUid();
9094            final int callingUserId = UserHandle.getUserId(callingUid);
9095            if (getInstantAppPackageName(callingUid) != null) {
9096                if (!isCallerSameApp(packageName, callingUid)) {
9097                    return;
9098                }
9099            } else {
9100                if (isInstantApp(packageName, callingUserId)) {
9101                    return;
9102                }
9103            }
9104            notifyPackageUseLocked(packageName, reason);
9105        }
9106    }
9107
9108    @GuardedBy("mPackages")
9109    private void notifyPackageUseLocked(String packageName, int reason) {
9110        final PackageParser.Package p = mPackages.get(packageName);
9111        if (p == null) {
9112            return;
9113        }
9114        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9115    }
9116
9117    @Override
9118    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9119            List<String> classPaths, String loaderIsa) {
9120        int userId = UserHandle.getCallingUserId();
9121        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9122        if (ai == null) {
9123            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9124                + loadingPackageName + ", user=" + userId);
9125            return;
9126        }
9127        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9128    }
9129
9130    @Override
9131    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9132            IDexModuleRegisterCallback callback) {
9133        int userId = UserHandle.getCallingUserId();
9134        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9135        DexManager.RegisterDexModuleResult result;
9136        if (ai == null) {
9137            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9138                     " calling user. package=" + packageName + ", user=" + userId);
9139            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9140        } else {
9141            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9142        }
9143
9144        if (callback != null) {
9145            mHandler.post(() -> {
9146                try {
9147                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9148                } catch (RemoteException e) {
9149                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9150                }
9151            });
9152        }
9153    }
9154
9155    /**
9156     * Ask the package manager to perform a dex-opt with the given compiler filter.
9157     *
9158     * Note: exposed only for the shell command to allow moving packages explicitly to a
9159     *       definite state.
9160     */
9161    @Override
9162    public boolean performDexOptMode(String packageName,
9163            boolean checkProfiles, String targetCompilerFilter, boolean force,
9164            boolean bootComplete, String splitName) {
9165        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9166                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9167                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9168        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9169                targetCompilerFilter, splitName, flags));
9170    }
9171
9172    /**
9173     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9174     * secondary dex files belonging to the given package.
9175     *
9176     * Note: exposed only for the shell command to allow moving packages explicitly to a
9177     *       definite state.
9178     */
9179    @Override
9180    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9181            boolean force) {
9182        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9183                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9184                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9185                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9186        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9187    }
9188
9189    /*package*/ boolean performDexOpt(DexoptOptions options) {
9190        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9191            return false;
9192        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9193            return false;
9194        }
9195
9196        if (options.isDexoptOnlySecondaryDex()) {
9197            return mDexManager.dexoptSecondaryDex(options);
9198        } else {
9199            int dexoptStatus = performDexOptWithStatus(options);
9200            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9201        }
9202    }
9203
9204    /**
9205     * Perform dexopt on the given package and return one of following result:
9206     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9207     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9208     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9209     */
9210    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9211        return performDexOptTraced(options);
9212    }
9213
9214    private int performDexOptTraced(DexoptOptions options) {
9215        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9216        try {
9217            return performDexOptInternal(options);
9218        } finally {
9219            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9220        }
9221    }
9222
9223    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9224    // if the package can now be considered up to date for the given filter.
9225    private int performDexOptInternal(DexoptOptions options) {
9226        PackageParser.Package p;
9227        synchronized (mPackages) {
9228            p = mPackages.get(options.getPackageName());
9229            if (p == null) {
9230                // Package could not be found. Report failure.
9231                return PackageDexOptimizer.DEX_OPT_FAILED;
9232            }
9233            mPackageUsage.maybeWriteAsync(mPackages);
9234            mCompilerStats.maybeWriteAsync();
9235        }
9236        long callingId = Binder.clearCallingIdentity();
9237        try {
9238            synchronized (mInstallLock) {
9239                return performDexOptInternalWithDependenciesLI(p, options);
9240            }
9241        } finally {
9242            Binder.restoreCallingIdentity(callingId);
9243        }
9244    }
9245
9246    public ArraySet<String> getOptimizablePackages() {
9247        ArraySet<String> pkgs = new ArraySet<String>();
9248        synchronized (mPackages) {
9249            for (PackageParser.Package p : mPackages.values()) {
9250                if (PackageDexOptimizer.canOptimizePackage(p)) {
9251                    pkgs.add(p.packageName);
9252                }
9253            }
9254        }
9255        return pkgs;
9256    }
9257
9258    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9259            DexoptOptions options) {
9260        // Select the dex optimizer based on the force parameter.
9261        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9262        //       allocate an object here.
9263        PackageDexOptimizer pdo = options.isForce()
9264                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9265                : mPackageDexOptimizer;
9266
9267        // Dexopt all dependencies first. Note: we ignore the return value and march on
9268        // on errors.
9269        // Note that we are going to call performDexOpt on those libraries as many times as
9270        // they are referenced in packages. When we do a batch of performDexOpt (for example
9271        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9272        // and the first package that uses the library will dexopt it. The
9273        // others will see that the compiled code for the library is up to date.
9274        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9275        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9276        if (!deps.isEmpty()) {
9277            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9278                    options.getCompilationReason(), options.getCompilerFilter(),
9279                    options.getSplitName(),
9280                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9281            for (PackageParser.Package depPackage : deps) {
9282                // TODO: Analyze and investigate if we (should) profile libraries.
9283                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9284                        getOrCreateCompilerPackageStats(depPackage),
9285                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9286            }
9287        }
9288        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9289                getOrCreateCompilerPackageStats(p),
9290                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9291    }
9292
9293    /**
9294     * Reconcile the information we have about the secondary dex files belonging to
9295     * {@code packagName} and the actual dex files. For all dex files that were
9296     * deleted, update the internal records and delete the generated oat files.
9297     */
9298    @Override
9299    public void reconcileSecondaryDexFiles(String packageName) {
9300        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9301            return;
9302        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9303            return;
9304        }
9305        mDexManager.reconcileSecondaryDexFiles(packageName);
9306    }
9307
9308    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9309    // a reference there.
9310    /*package*/ DexManager getDexManager() {
9311        return mDexManager;
9312    }
9313
9314    /**
9315     * Execute the background dexopt job immediately.
9316     */
9317    @Override
9318    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9319        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9320            return false;
9321        }
9322        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9323    }
9324
9325    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9326        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9327                || p.usesStaticLibraries != null) {
9328            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9329            Set<String> collectedNames = new HashSet<>();
9330            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9331
9332            retValue.remove(p);
9333
9334            return retValue;
9335        } else {
9336            return Collections.emptyList();
9337        }
9338    }
9339
9340    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9341            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9342        if (!collectedNames.contains(p.packageName)) {
9343            collectedNames.add(p.packageName);
9344            collected.add(p);
9345
9346            if (p.usesLibraries != null) {
9347                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9348                        null, collected, collectedNames);
9349            }
9350            if (p.usesOptionalLibraries != null) {
9351                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9352                        null, collected, collectedNames);
9353            }
9354            if (p.usesStaticLibraries != null) {
9355                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9356                        p.usesStaticLibrariesVersions, collected, collectedNames);
9357            }
9358        }
9359    }
9360
9361    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9362            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9363        final int libNameCount = libs.size();
9364        for (int i = 0; i < libNameCount; i++) {
9365            String libName = libs.get(i);
9366            long version = (versions != null && versions.length == libNameCount)
9367                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9368            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9369            if (libPkg != null) {
9370                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9371            }
9372        }
9373    }
9374
9375    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9376        synchronized (mPackages) {
9377            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9378            if (libEntry != null) {
9379                return mPackages.get(libEntry.apk);
9380            }
9381            return null;
9382        }
9383    }
9384
9385    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9386        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9387        if (versionedLib == null) {
9388            return null;
9389        }
9390        return versionedLib.get(version);
9391    }
9392
9393    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9394        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9395                pkg.staticSharedLibName);
9396        if (versionedLib == null) {
9397            return null;
9398        }
9399        long previousLibVersion = -1;
9400        final int versionCount = versionedLib.size();
9401        for (int i = 0; i < versionCount; i++) {
9402            final long libVersion = versionedLib.keyAt(i);
9403            if (libVersion < pkg.staticSharedLibVersion) {
9404                previousLibVersion = Math.max(previousLibVersion, libVersion);
9405            }
9406        }
9407        if (previousLibVersion >= 0) {
9408            return versionedLib.get(previousLibVersion);
9409        }
9410        return null;
9411    }
9412
9413    public void shutdown() {
9414        mPackageUsage.writeNow(mPackages);
9415        mCompilerStats.writeNow();
9416        mDexManager.writePackageDexUsageNow();
9417    }
9418
9419    @Override
9420    public void dumpProfiles(String packageName) {
9421        PackageParser.Package pkg;
9422        synchronized (mPackages) {
9423            pkg = mPackages.get(packageName);
9424            if (pkg == null) {
9425                throw new IllegalArgumentException("Unknown package: " + packageName);
9426            }
9427        }
9428        /* Only the shell, root, or the app user should be able to dump profiles. */
9429        int callingUid = Binder.getCallingUid();
9430        if (callingUid != Process.SHELL_UID &&
9431            callingUid != Process.ROOT_UID &&
9432            callingUid != pkg.applicationInfo.uid) {
9433            throw new SecurityException("dumpProfiles");
9434        }
9435
9436        synchronized (mInstallLock) {
9437            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9438            mArtManagerService.dumpProfiles(pkg);
9439            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9440        }
9441    }
9442
9443    @Override
9444    public void forceDexOpt(String packageName) {
9445        enforceSystemOrRoot("forceDexOpt");
9446
9447        PackageParser.Package pkg;
9448        synchronized (mPackages) {
9449            pkg = mPackages.get(packageName);
9450            if (pkg == null) {
9451                throw new IllegalArgumentException("Unknown package: " + packageName);
9452            }
9453        }
9454
9455        synchronized (mInstallLock) {
9456            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9457
9458            // Whoever is calling forceDexOpt wants a compiled package.
9459            // Don't use profiles since that may cause compilation to be skipped.
9460            final int res = performDexOptInternalWithDependenciesLI(
9461                    pkg,
9462                    new DexoptOptions(packageName,
9463                            getDefaultCompilerFilter(),
9464                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9465
9466            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9467            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9468                throw new IllegalStateException("Failed to dexopt: " + res);
9469            }
9470        }
9471    }
9472
9473    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9474        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9475            Slog.w(TAG, "Unable to update from " + oldPkg.name
9476                    + " to " + newPkg.packageName
9477                    + ": old package not in system partition");
9478            return false;
9479        } else if (mPackages.get(oldPkg.name) != null) {
9480            Slog.w(TAG, "Unable to update from " + oldPkg.name
9481                    + " to " + newPkg.packageName
9482                    + ": old package still exists");
9483            return false;
9484        }
9485        return true;
9486    }
9487
9488    void removeCodePathLI(File codePath) {
9489        if (codePath.isDirectory()) {
9490            try {
9491                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9492            } catch (InstallerException e) {
9493                Slog.w(TAG, "Failed to remove code path", e);
9494            }
9495        } else {
9496            codePath.delete();
9497        }
9498    }
9499
9500    private int[] resolveUserIds(int userId) {
9501        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9502    }
9503
9504    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9505        if (pkg == null) {
9506            Slog.wtf(TAG, "Package was null!", new Throwable());
9507            return;
9508        }
9509        clearAppDataLeafLIF(pkg, userId, flags);
9510        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9511        for (int i = 0; i < childCount; i++) {
9512            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9513        }
9514
9515        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9516    }
9517
9518    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9519        final PackageSetting ps;
9520        synchronized (mPackages) {
9521            ps = mSettings.mPackages.get(pkg.packageName);
9522        }
9523        for (int realUserId : resolveUserIds(userId)) {
9524            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9525            try {
9526                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9527                        ceDataInode);
9528            } catch (InstallerException e) {
9529                Slog.w(TAG, String.valueOf(e));
9530            }
9531        }
9532    }
9533
9534    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9535        if (pkg == null) {
9536            Slog.wtf(TAG, "Package was null!", new Throwable());
9537            return;
9538        }
9539        destroyAppDataLeafLIF(pkg, userId, flags);
9540        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9541        for (int i = 0; i < childCount; i++) {
9542            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9543        }
9544    }
9545
9546    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9547        final PackageSetting ps;
9548        synchronized (mPackages) {
9549            ps = mSettings.mPackages.get(pkg.packageName);
9550        }
9551        for (int realUserId : resolveUserIds(userId)) {
9552            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9553            try {
9554                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9555                        ceDataInode);
9556            } catch (InstallerException e) {
9557                Slog.w(TAG, String.valueOf(e));
9558            }
9559            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9560        }
9561    }
9562
9563    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9564        if (pkg == null) {
9565            Slog.wtf(TAG, "Package was null!", new Throwable());
9566            return;
9567        }
9568        destroyAppProfilesLeafLIF(pkg);
9569        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9570        for (int i = 0; i < childCount; i++) {
9571            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9572        }
9573    }
9574
9575    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9576        try {
9577            mInstaller.destroyAppProfiles(pkg.packageName);
9578        } catch (InstallerException e) {
9579            Slog.w(TAG, String.valueOf(e));
9580        }
9581    }
9582
9583    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9584        if (pkg == null) {
9585            Slog.wtf(TAG, "Package was null!", new Throwable());
9586            return;
9587        }
9588        mArtManagerService.clearAppProfiles(pkg);
9589        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9590        for (int i = 0; i < childCount; i++) {
9591            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9592        }
9593    }
9594
9595    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9596            long lastUpdateTime) {
9597        // Set parent install/update time
9598        PackageSetting ps = (PackageSetting) pkg.mExtras;
9599        if (ps != null) {
9600            ps.firstInstallTime = firstInstallTime;
9601            ps.lastUpdateTime = lastUpdateTime;
9602        }
9603        // Set children install/update time
9604        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9605        for (int i = 0; i < childCount; i++) {
9606            PackageParser.Package childPkg = pkg.childPackages.get(i);
9607            ps = (PackageSetting) childPkg.mExtras;
9608            if (ps != null) {
9609                ps.firstInstallTime = firstInstallTime;
9610                ps.lastUpdateTime = lastUpdateTime;
9611            }
9612        }
9613    }
9614
9615    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9616            SharedLibraryEntry file,
9617            PackageParser.Package changingLib) {
9618        if (file.path != null) {
9619            usesLibraryFiles.add(file.path);
9620            return;
9621        }
9622        PackageParser.Package p = mPackages.get(file.apk);
9623        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9624            // If we are doing this while in the middle of updating a library apk,
9625            // then we need to make sure to use that new apk for determining the
9626            // dependencies here.  (We haven't yet finished committing the new apk
9627            // to the package manager state.)
9628            if (p == null || p.packageName.equals(changingLib.packageName)) {
9629                p = changingLib;
9630            }
9631        }
9632        if (p != null) {
9633            usesLibraryFiles.addAll(p.getAllCodePaths());
9634            if (p.usesLibraryFiles != null) {
9635                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9636            }
9637        }
9638    }
9639
9640    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9641            PackageParser.Package changingLib) throws PackageManagerException {
9642        if (pkg == null) {
9643            return;
9644        }
9645        // The collection used here must maintain the order of addition (so
9646        // that libraries are searched in the correct order) and must have no
9647        // duplicates.
9648        Set<String> usesLibraryFiles = null;
9649        if (pkg.usesLibraries != null) {
9650            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9651                    null, null, pkg.packageName, changingLib, true,
9652                    pkg.applicationInfo.targetSdkVersion, null);
9653        }
9654        if (pkg.usesStaticLibraries != null) {
9655            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9656                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9657                    pkg.packageName, changingLib, true,
9658                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9659        }
9660        if (pkg.usesOptionalLibraries != null) {
9661            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9662                    null, null, pkg.packageName, changingLib, false,
9663                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9664        }
9665        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9666            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9667        } else {
9668            pkg.usesLibraryFiles = null;
9669        }
9670    }
9671
9672    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9673            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9674            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9675            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9676            throws PackageManagerException {
9677        final int libCount = requestedLibraries.size();
9678        for (int i = 0; i < libCount; i++) {
9679            final String libName = requestedLibraries.get(i);
9680            final long libVersion = requiredVersions != null ? requiredVersions[i]
9681                    : SharedLibraryInfo.VERSION_UNDEFINED;
9682            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9683            if (libEntry == null) {
9684                if (required) {
9685                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9686                            "Package " + packageName + " requires unavailable shared library "
9687                                    + libName + "; failing!");
9688                } else if (DEBUG_SHARED_LIBRARIES) {
9689                    Slog.i(TAG, "Package " + packageName
9690                            + " desires unavailable shared library "
9691                            + libName + "; ignoring!");
9692                }
9693            } else {
9694                if (requiredVersions != null && requiredCertDigests != null) {
9695                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9696                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9697                            "Package " + packageName + " requires unavailable static shared"
9698                                    + " library " + libName + " version "
9699                                    + libEntry.info.getLongVersion() + "; failing!");
9700                    }
9701
9702                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9703                    if (libPkg == null) {
9704                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9705                                "Package " + packageName + " requires unavailable static shared"
9706                                        + " library; failing!");
9707                    }
9708
9709                    final String[] expectedCertDigests = requiredCertDigests[i];
9710
9711
9712                    if (expectedCertDigests.length > 1) {
9713
9714                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9715                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9716                                ? PackageUtils.computeSignaturesSha256Digests(
9717                                libPkg.mSigningDetails.signatures)
9718                                : PackageUtils.computeSignaturesSha256Digests(
9719                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9720
9721                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9722                        // target O we don't parse the "additional-certificate" tags similarly
9723                        // how we only consider all certs only for apps targeting O (see above).
9724                        // Therefore, the size check is safe to make.
9725                        if (expectedCertDigests.length != libCertDigests.length) {
9726                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9727                                    "Package " + packageName + " requires differently signed" +
9728                                            " static shared library; failing!");
9729                        }
9730
9731                        // Use a predictable order as signature order may vary
9732                        Arrays.sort(libCertDigests);
9733                        Arrays.sort(expectedCertDigests);
9734
9735                        final int certCount = libCertDigests.length;
9736                        for (int j = 0; j < certCount; j++) {
9737                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9738                                throw new PackageManagerException(
9739                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9740                                        "Package " + packageName + " requires differently signed" +
9741                                                " static shared library; failing!");
9742                            }
9743                        }
9744                    } else {
9745
9746                        // lib signing cert could have rotated beyond the one expected, check to see
9747                        // if the new one has been blessed by the old
9748                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9749                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9750                            throw new PackageManagerException(
9751                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9752                                    "Package " + packageName + " requires differently signed" +
9753                                            " static shared library; failing!");
9754                        }
9755                    }
9756                }
9757
9758                if (outUsedLibraries == null) {
9759                    // Use LinkedHashSet to preserve the order of files added to
9760                    // usesLibraryFiles while eliminating duplicates.
9761                    outUsedLibraries = new LinkedHashSet<>();
9762                }
9763                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9764            }
9765        }
9766        return outUsedLibraries;
9767    }
9768
9769    private static boolean hasString(List<String> list, List<String> which) {
9770        if (list == null) {
9771            return false;
9772        }
9773        for (int i=list.size()-1; i>=0; i--) {
9774            for (int j=which.size()-1; j>=0; j--) {
9775                if (which.get(j).equals(list.get(i))) {
9776                    return true;
9777                }
9778            }
9779        }
9780        return false;
9781    }
9782
9783    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9784            PackageParser.Package changingPkg) {
9785        ArrayList<PackageParser.Package> res = null;
9786        for (PackageParser.Package pkg : mPackages.values()) {
9787            if (changingPkg != null
9788                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9789                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9790                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9791                            changingPkg.staticSharedLibName)) {
9792                return null;
9793            }
9794            if (res == null) {
9795                res = new ArrayList<>();
9796            }
9797            res.add(pkg);
9798            try {
9799                updateSharedLibrariesLPr(pkg, changingPkg);
9800            } catch (PackageManagerException e) {
9801                // If a system app update or an app and a required lib missing we
9802                // delete the package and for updated system apps keep the data as
9803                // it is better for the user to reinstall than to be in an limbo
9804                // state. Also libs disappearing under an app should never happen
9805                // - just in case.
9806                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9807                    final int flags = pkg.isUpdatedSystemApp()
9808                            ? PackageManager.DELETE_KEEP_DATA : 0;
9809                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9810                            flags , null, true, null);
9811                }
9812                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9813            }
9814        }
9815        return res;
9816    }
9817
9818    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9819            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9820            @Nullable UserHandle user) throws PackageManagerException {
9821        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9822        // If the package has children and this is the first dive in the function
9823        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9824        // whether all packages (parent and children) would be successfully scanned
9825        // before the actual scan since scanning mutates internal state and we want
9826        // to atomically install the package and its children.
9827        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9828            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9829                scanFlags |= SCAN_CHECK_ONLY;
9830            }
9831        } else {
9832            scanFlags &= ~SCAN_CHECK_ONLY;
9833        }
9834
9835        final PackageParser.Package scannedPkg;
9836        try {
9837            // Scan the parent
9838            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9839            // Scan the children
9840            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9841            for (int i = 0; i < childCount; i++) {
9842                PackageParser.Package childPkg = pkg.childPackages.get(i);
9843                scanPackageNewLI(childPkg, parseFlags,
9844                        scanFlags, currentTime, user);
9845            }
9846        } finally {
9847            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9848        }
9849
9850        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9851            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9852        }
9853
9854        return scannedPkg;
9855    }
9856
9857    /** The result of a package scan. */
9858    private static class ScanResult {
9859        /** Whether or not the package scan was successful */
9860        public final boolean success;
9861        /**
9862         * The final package settings. This may be the same object passed in
9863         * the {@link ScanRequest}, but, with modified values.
9864         */
9865        @Nullable public final PackageSetting pkgSetting;
9866        /** ABI code paths that have changed in the package scan */
9867        @Nullable public final List<String> changedAbiCodePath;
9868        public ScanResult(
9869                boolean success,
9870                @Nullable PackageSetting pkgSetting,
9871                @Nullable List<String> changedAbiCodePath) {
9872            this.success = success;
9873            this.pkgSetting = pkgSetting;
9874            this.changedAbiCodePath = changedAbiCodePath;
9875        }
9876    }
9877
9878    /** A package to be scanned */
9879    private static class ScanRequest {
9880        /** The parsed package */
9881        @NonNull public final PackageParser.Package pkg;
9882        /** The package this package replaces */
9883        @Nullable public final PackageParser.Package oldPkg;
9884        /** Shared user settings, if the package has a shared user */
9885        @Nullable public final SharedUserSetting sharedUserSetting;
9886        /**
9887         * Package settings of the currently installed version.
9888         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9889         * during scan.
9890         */
9891        @Nullable public final PackageSetting pkgSetting;
9892        /** A copy of the settings for the currently installed version */
9893        @Nullable public final PackageSetting oldPkgSetting;
9894        /** Package settings for the disabled version on the /system partition */
9895        @Nullable public final PackageSetting disabledPkgSetting;
9896        /** Package settings for the installed version under its original package name */
9897        @Nullable public final PackageSetting originalPkgSetting;
9898        /** The real package name of a renamed application */
9899        @Nullable public final String realPkgName;
9900        public final @ParseFlags int parseFlags;
9901        public final @ScanFlags int scanFlags;
9902        /** The user for which the package is being scanned */
9903        @Nullable public final UserHandle user;
9904        /** Whether or not the platform package is being scanned */
9905        public final boolean isPlatformPackage;
9906        public ScanRequest(
9907                @NonNull PackageParser.Package pkg,
9908                @Nullable SharedUserSetting sharedUserSetting,
9909                @Nullable PackageParser.Package oldPkg,
9910                @Nullable PackageSetting pkgSetting,
9911                @Nullable PackageSetting disabledPkgSetting,
9912                @Nullable PackageSetting originalPkgSetting,
9913                @Nullable String realPkgName,
9914                @ParseFlags int parseFlags,
9915                @ScanFlags int scanFlags,
9916                boolean isPlatformPackage,
9917                @Nullable UserHandle user) {
9918            this.pkg = pkg;
9919            this.oldPkg = oldPkg;
9920            this.pkgSetting = pkgSetting;
9921            this.sharedUserSetting = sharedUserSetting;
9922            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9923            this.disabledPkgSetting = disabledPkgSetting;
9924            this.originalPkgSetting = originalPkgSetting;
9925            this.realPkgName = realPkgName;
9926            this.parseFlags = parseFlags;
9927            this.scanFlags = scanFlags;
9928            this.isPlatformPackage = isPlatformPackage;
9929            this.user = user;
9930        }
9931    }
9932
9933    /**
9934     * Returns the actual scan flags depending upon the state of the other settings.
9935     * <p>Updated system applications will not have the following flags set
9936     * by default and need to be adjusted after the fact:
9937     * <ul>
9938     * <li>{@link #SCAN_AS_SYSTEM}</li>
9939     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9940     * <li>{@link #SCAN_AS_OEM}</li>
9941     * <li>{@link #SCAN_AS_VENDOR}</li>
9942     * <li>{@link #SCAN_AS_PRODUCT}</li>
9943     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9944     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9945     * </ul>
9946     */
9947    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9948            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9949            PackageParser.Package pkg) {
9950        if (disabledPkgSetting != null) {
9951            // updated system application, must at least have SCAN_AS_SYSTEM
9952            scanFlags |= SCAN_AS_SYSTEM;
9953            if ((disabledPkgSetting.pkgPrivateFlags
9954                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9955                scanFlags |= SCAN_AS_PRIVILEGED;
9956            }
9957            if ((disabledPkgSetting.pkgPrivateFlags
9958                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9959                scanFlags |= SCAN_AS_OEM;
9960            }
9961            if ((disabledPkgSetting.pkgPrivateFlags
9962                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9963                scanFlags |= SCAN_AS_VENDOR;
9964            }
9965            if ((disabledPkgSetting.pkgPrivateFlags
9966                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9967                scanFlags |= SCAN_AS_PRODUCT;
9968            }
9969        }
9970        if (pkgSetting != null) {
9971            final int userId = ((user == null) ? 0 : user.getIdentifier());
9972            if (pkgSetting.getInstantApp(userId)) {
9973                scanFlags |= SCAN_AS_INSTANT_APP;
9974            }
9975            if (pkgSetting.getVirtulalPreload(userId)) {
9976                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9977            }
9978        }
9979
9980        // Scan as privileged apps that share a user with a priv-app.
9981        final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
9982                && SystemProperties.getInt("ro.vndk.version", 28) < 28;
9983        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
9984                && !pkg.isPrivileged()
9985                && (pkg.mSharedUserId != null)
9986                && !skipVendorPrivilegeScan) {
9987            SharedUserSetting sharedUserSetting = null;
9988            try {
9989                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9990            } catch (PackageManagerException ignore) {}
9991            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9992                // Exempt SharedUsers signed with the platform key.
9993                // TODO(b/72378145) Fix this exemption. Force signature apps
9994                // to whitelist their privileged permissions just like other
9995                // priv-apps.
9996                synchronized (mPackages) {
9997                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9998                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9999                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10000                        scanFlags |= SCAN_AS_PRIVILEGED;
10001                    }
10002                }
10003            }
10004        }
10005
10006        return scanFlags;
10007    }
10008
10009    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10010    // the results / removing app data needs to be moved up a level to the callers of this
10011    // method. Also, we need to solve the problem of potentially creating a new shared user
10012    // setting. That can probably be done later and patch things up after the fact.
10013    @GuardedBy("mInstallLock")
10014    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10015            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10016            @Nullable UserHandle user) throws PackageManagerException {
10017
10018        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10019        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10020        if (realPkgName != null) {
10021            ensurePackageRenamed(pkg, renamedPkgName);
10022        }
10023        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10024        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10025        final PackageSetting disabledPkgSetting =
10026                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10027
10028        if (mTransferedPackages.contains(pkg.packageName)) {
10029            Slog.w(TAG, "Package " + pkg.packageName
10030                    + " was transferred to another, but its .apk remains");
10031        }
10032
10033        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10034        synchronized (mPackages) {
10035            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10036            assertPackageIsValid(pkg, parseFlags, scanFlags);
10037
10038            SharedUserSetting sharedUserSetting = null;
10039            if (pkg.mSharedUserId != null) {
10040                // SIDE EFFECTS; may potentially allocate a new shared user
10041                sharedUserSetting = mSettings.getSharedUserLPw(
10042                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10043                if (DEBUG_PACKAGE_SCANNING) {
10044                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10045                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10046                                + " (uid=" + sharedUserSetting.userId + "):"
10047                                + " packages=" + sharedUserSetting.packages);
10048                }
10049            }
10050
10051            boolean scanSucceeded = false;
10052            try {
10053                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10054                        pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10055                        originalPkgSetting, realPkgName, parseFlags, scanFlags,
10056                        (pkg == mPlatformPackage), user);
10057                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10058                if (result.success) {
10059                    commitScanResultsLocked(request, result);
10060                }
10061                scanSucceeded = true;
10062            } finally {
10063                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10064                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10065                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10066                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10067                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10068                  }
10069            }
10070        }
10071        return pkg;
10072    }
10073
10074    /**
10075     * Commits the package scan and modifies system state.
10076     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10077     * of committing the package, leaving the system in an inconsistent state.
10078     * This needs to be fixed so, once we get to this point, no errors are
10079     * possible and the system is not left in an inconsistent state.
10080     */
10081    @GuardedBy("mPackages")
10082    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10083            throws PackageManagerException {
10084        final PackageParser.Package pkg = request.pkg;
10085        final PackageParser.Package oldPkg = request.oldPkg;
10086        final @ParseFlags int parseFlags = request.parseFlags;
10087        final @ScanFlags int scanFlags = request.scanFlags;
10088        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10089        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10090        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10091        final UserHandle user = request.user;
10092        final String realPkgName = request.realPkgName;
10093        final PackageSetting pkgSetting = result.pkgSetting;
10094        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10095        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10096
10097        if (newPkgSettingCreated) {
10098            if (originalPkgSetting != null) {
10099                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10100            }
10101            // THROWS: when we can't allocate a user id. add call to check if there's
10102            // enough space to ensure we won't throw; otherwise, don't modify state
10103            mSettings.addUserToSettingLPw(pkgSetting);
10104
10105            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10106                mTransferedPackages.add(originalPkgSetting.name);
10107            }
10108        }
10109        // TODO(toddke): Consider a method specifically for modifying the Package object
10110        // post scan; or, moving this stuff out of the Package object since it has nothing
10111        // to do with the package on disk.
10112        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10113        // for creating the application ID. If we did this earlier, we would be saving the
10114        // correct ID.
10115        pkg.applicationInfo.uid = pkgSetting.appId;
10116
10117        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10118
10119        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10120            mTransferedPackages.add(pkg.packageName);
10121        }
10122
10123        // THROWS: when requested libraries that can't be found. it only changes
10124        // the state of the passed in pkg object, so, move to the top of the method
10125        // and allow it to abort
10126        if ((scanFlags & SCAN_BOOTING) == 0
10127                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10128            // Check all shared libraries and map to their actual file path.
10129            // We only do this here for apps not on a system dir, because those
10130            // are the only ones that can fail an install due to this.  We
10131            // will take care of the system apps by updating all of their
10132            // library paths after the scan is done. Also during the initial
10133            // scan don't update any libs as we do this wholesale after all
10134            // apps are scanned to avoid dependency based scanning.
10135            updateSharedLibrariesLPr(pkg, null);
10136        }
10137
10138        // All versions of a static shared library are referenced with the same
10139        // package name. Internally, we use a synthetic package name to allow
10140        // multiple versions of the same shared library to be installed. So,
10141        // we need to generate the synthetic package name of the latest shared
10142        // library in order to compare signatures.
10143        PackageSetting signatureCheckPs = pkgSetting;
10144        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10145            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10146            if (libraryEntry != null) {
10147                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10148            }
10149        }
10150
10151        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10152        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10153            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10154                // We just determined the app is signed correctly, so bring
10155                // over the latest parsed certs.
10156                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10157            } else {
10158                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10159                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10160                            "Package " + pkg.packageName + " upgrade keys do not match the "
10161                                    + "previously installed version");
10162                } else {
10163                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10164                    String msg = "System package " + pkg.packageName
10165                            + " signature changed; retaining data.";
10166                    reportSettingsProblem(Log.WARN, msg);
10167                }
10168            }
10169        } else {
10170            try {
10171                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10172                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10173                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10174                        pkg.mSigningDetails, compareCompat, compareRecover);
10175                // The new KeySets will be re-added later in the scanning process.
10176                if (compatMatch) {
10177                    synchronized (mPackages) {
10178                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10179                    }
10180                }
10181                // We just determined the app is signed correctly, so bring
10182                // over the latest parsed certs.
10183                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10184
10185
10186                // if this is is a sharedUser, check to see if the new package is signed by a newer
10187                // signing certificate than the existing one, and if so, copy over the new details
10188                if (signatureCheckPs.sharedUser != null
10189                        && pkg.mSigningDetails.hasAncestor(
10190                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10191                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10192                }
10193            } catch (PackageManagerException e) {
10194                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10195                    throw e;
10196                }
10197                // The signature has changed, but this package is in the system
10198                // image...  let's recover!
10199                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10200                // If the system app is part of a shared user we allow that shared user to change
10201                // signatures as well in part as part of an OTA.
10202                if (signatureCheckPs.sharedUser != null) {
10203                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10204                }
10205                // File a report about this.
10206                String msg = "System package " + pkg.packageName
10207                        + " signature changed; retaining data.";
10208                reportSettingsProblem(Log.WARN, msg);
10209            } catch (IllegalArgumentException e) {
10210
10211                // should never happen: certs matched when checking, but not when comparing
10212                // old to new for sharedUser
10213                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10214                        "Signing certificates comparison made on incomparable signing details"
10215                        + " but somehow passed verifySignatures!");
10216            }
10217        }
10218
10219        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10220            // This package wants to adopt ownership of permissions from
10221            // another package.
10222            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10223                final String origName = pkg.mAdoptPermissions.get(i);
10224                final PackageSetting orig = mSettings.getPackageLPr(origName);
10225                if (orig != null) {
10226                    if (verifyPackageUpdateLPr(orig, pkg)) {
10227                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10228                                + pkg.packageName);
10229                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10230                    }
10231                }
10232            }
10233        }
10234
10235        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10236            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10237                final String codePathString = changedAbiCodePath.get(i);
10238                try {
10239                    mInstaller.rmdex(codePathString,
10240                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10241                } catch (InstallerException ignored) {
10242                }
10243            }
10244        }
10245
10246        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10247            if (oldPkgSetting != null) {
10248                synchronized (mPackages) {
10249                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10250                }
10251            }
10252        } else {
10253            final int userId = user == null ? 0 : user.getIdentifier();
10254            // Modify state for the given package setting
10255            commitPackageSettings(pkg, oldPkg, pkgSetting, user, scanFlags,
10256                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10257            if (pkgSetting.getInstantApp(userId)) {
10258                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10259            }
10260        }
10261    }
10262
10263    /**
10264     * Returns the "real" name of the package.
10265     * <p>This may differ from the package's actual name if the application has already
10266     * been installed under one of this package's original names.
10267     */
10268    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10269            @Nullable String renamedPkgName) {
10270        if (isPackageRenamed(pkg, renamedPkgName)) {
10271            return pkg.mRealPackage;
10272        }
10273        return null;
10274    }
10275
10276    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10277    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10278            @Nullable String renamedPkgName) {
10279        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10280    }
10281
10282    /**
10283     * Returns the original package setting.
10284     * <p>A package can migrate its name during an update. In this scenario, a package
10285     * designates a set of names that it considers as one of its original names.
10286     * <p>An original package must be signed identically and it must have the same
10287     * shared user [if any].
10288     */
10289    @GuardedBy("mPackages")
10290    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10291            @Nullable String renamedPkgName) {
10292        if (!isPackageRenamed(pkg, renamedPkgName)) {
10293            return null;
10294        }
10295        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10296            final PackageSetting originalPs =
10297                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10298            if (originalPs != null) {
10299                // the package is already installed under its original name...
10300                // but, should we use it?
10301                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10302                    // the new package is incompatible with the original
10303                    continue;
10304                } else if (originalPs.sharedUser != null) {
10305                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10306                        // the shared user id is incompatible with the original
10307                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10308                                + " to " + pkg.packageName + ": old uid "
10309                                + originalPs.sharedUser.name
10310                                + " differs from " + pkg.mSharedUserId);
10311                        continue;
10312                    }
10313                    // TODO: Add case when shared user id is added [b/28144775]
10314                } else {
10315                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10316                            + pkg.packageName + " to old name " + originalPs.name);
10317                }
10318                return originalPs;
10319            }
10320        }
10321        return null;
10322    }
10323
10324    /**
10325     * Renames the package if it was installed under a different name.
10326     * <p>When we've already installed the package under an original name, update
10327     * the new package so we can continue to have the old name.
10328     */
10329    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10330            @NonNull String renamedPackageName) {
10331        if (pkg.mOriginalPackages == null
10332                || !pkg.mOriginalPackages.contains(renamedPackageName)
10333                || pkg.packageName.equals(renamedPackageName)) {
10334            return;
10335        }
10336        pkg.setPackageName(renamedPackageName);
10337    }
10338
10339    /**
10340     * Just scans the package without any side effects.
10341     * <p>Not entirely true at the moment. There is still one side effect -- this
10342     * method potentially modifies a live {@link PackageSetting} object representing
10343     * the package being scanned. This will be resolved in the future.
10344     *
10345     * @param request Information about the package to be scanned
10346     * @param isUnderFactoryTest Whether or not the device is under factory test
10347     * @param currentTime The current time, in millis
10348     * @return The results of the scan
10349     */
10350    @GuardedBy("mInstallLock")
10351    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10352            boolean isUnderFactoryTest, long currentTime)
10353                    throws PackageManagerException {
10354        final PackageParser.Package pkg = request.pkg;
10355        PackageSetting pkgSetting = request.pkgSetting;
10356        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10357        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10358        final @ParseFlags int parseFlags = request.parseFlags;
10359        final @ScanFlags int scanFlags = request.scanFlags;
10360        final String realPkgName = request.realPkgName;
10361        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10362        final UserHandle user = request.user;
10363        final boolean isPlatformPackage = request.isPlatformPackage;
10364
10365        List<String> changedAbiCodePath = null;
10366
10367        if (DEBUG_PACKAGE_SCANNING) {
10368            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10369                Log.d(TAG, "Scanning package " + pkg.packageName);
10370        }
10371
10372        if (Build.IS_DEBUGGABLE &&
10373                pkg.isPrivileged() &&
10374                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10375            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10376        }
10377
10378        // Initialize package source and resource directories
10379        final File scanFile = new File(pkg.codePath);
10380        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10381        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10382
10383        // We keep references to the derived CPU Abis from settings in oder to reuse
10384        // them in the case where we're not upgrading or booting for the first time.
10385        String primaryCpuAbiFromSettings = null;
10386        String secondaryCpuAbiFromSettings = null;
10387        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10388
10389        if (!needToDeriveAbi) {
10390            if (pkgSetting != null) {
10391                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10392                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10393            } else {
10394                // Re-scanning a system package after uninstalling updates; need to derive ABI
10395                needToDeriveAbi = true;
10396            }
10397        }
10398
10399        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10400            PackageManagerService.reportSettingsProblem(Log.WARN,
10401                    "Package " + pkg.packageName + " shared user changed from "
10402                            + (pkgSetting.sharedUser != null
10403                            ? pkgSetting.sharedUser.name : "<nothing>")
10404                            + " to "
10405                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10406                            + "; replacing with new");
10407            pkgSetting = null;
10408        }
10409
10410        String[] usesStaticLibraries = null;
10411        if (pkg.usesStaticLibraries != null) {
10412            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10413            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10414        }
10415        final boolean createNewPackage = (pkgSetting == null);
10416        if (createNewPackage) {
10417            final String parentPackageName = (pkg.parentPackage != null)
10418                    ? pkg.parentPackage.packageName : null;
10419            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10420            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10421            // REMOVE SharedUserSetting from method; update in a separate call
10422            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10423                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10424                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10425                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10426                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10427                    user, true /*allowInstall*/, instantApp, virtualPreload,
10428                    parentPackageName, pkg.getChildPackageNames(),
10429                    UserManagerService.getInstance(), usesStaticLibraries,
10430                    pkg.usesStaticLibrariesVersions);
10431        } else {
10432            // REMOVE SharedUserSetting from method; update in a separate call.
10433            //
10434            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10435            // secondaryCpuAbi are not known at this point so we always update them
10436            // to null here, only to reset them at a later point.
10437            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10438                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10439                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10440                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10441                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10442                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10443        }
10444        if (createNewPackage && originalPkgSetting != null) {
10445            // This is the initial transition from the original package, so,
10446            // fix up the new package's name now. We must do this after looking
10447            // up the package under its new name, so getPackageLP takes care of
10448            // fiddling things correctly.
10449            pkg.setPackageName(originalPkgSetting.name);
10450
10451            // File a report about this.
10452            String msg = "New package " + pkgSetting.realName
10453                    + " renamed to replace old package " + pkgSetting.name;
10454            reportSettingsProblem(Log.WARN, msg);
10455        }
10456
10457        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10458        // for existing packages, change the install state; but, only if it's explicitly specified
10459        if (!createNewPackage) {
10460            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10461            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10462            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10463        }
10464
10465        if (disabledPkgSetting != null) {
10466            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10467        }
10468
10469        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10470        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10471        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10472        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10473        // least restrictive selinux domain.
10474        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10475        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10476        // ensures that all packages continue to run in the same selinux domain.
10477        final int targetSdkVersion =
10478            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10479            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10480        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10481        // They currently can be if the sharedUser apps are signed with the platform key.
10482        final boolean isPrivileged = (sharedUserSetting != null) ?
10483            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10484
10485        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10486                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10487        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10488                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10489
10490        pkg.mExtras = pkgSetting;
10491        pkg.applicationInfo.processName = fixProcessName(
10492                pkg.applicationInfo.packageName,
10493                pkg.applicationInfo.processName);
10494
10495        if (!isPlatformPackage) {
10496            // Get all of our default paths setup
10497            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10498        }
10499
10500        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10501
10502        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10503            if (needToDeriveAbi) {
10504                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10505                final boolean extractNativeLibs = !pkg.isLibrary();
10506                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10507                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10508
10509                // Some system apps still use directory structure for native libraries
10510                // in which case we might end up not detecting abi solely based on apk
10511                // structure. Try to detect abi based on directory structure.
10512                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10513                        pkg.applicationInfo.primaryCpuAbi == null) {
10514                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10515                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10516                }
10517            } else {
10518                // This is not a first boot or an upgrade, don't bother deriving the
10519                // ABI during the scan. Instead, trust the value that was stored in the
10520                // package setting.
10521                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10522                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10523
10524                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10525
10526                if (DEBUG_ABI_SELECTION) {
10527                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10528                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10529                            pkg.applicationInfo.secondaryCpuAbi);
10530                }
10531            }
10532        } else {
10533            if ((scanFlags & SCAN_MOVE) != 0) {
10534                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10535                // but we already have this packages package info in the PackageSetting. We just
10536                // use that and derive the native library path based on the new codepath.
10537                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10538                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10539            }
10540
10541            // Set native library paths again. For moves, the path will be updated based on the
10542            // ABIs we've determined above. For non-moves, the path will be updated based on the
10543            // ABIs we determined during compilation, but the path will depend on the final
10544            // package path (after the rename away from the stage path).
10545            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10546        }
10547
10548        // This is a special case for the "system" package, where the ABI is
10549        // dictated by the zygote configuration (and init.rc). We should keep track
10550        // of this ABI so that we can deal with "normal" applications that run under
10551        // the same UID correctly.
10552        if (isPlatformPackage) {
10553            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10554                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10555        }
10556
10557        // If there's a mismatch between the abi-override in the package setting
10558        // and the abiOverride specified for the install. Warn about this because we
10559        // would've already compiled the app without taking the package setting into
10560        // account.
10561        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10562            if (cpuAbiOverride == null && pkg.packageName != null) {
10563                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10564                        " for package " + pkg.packageName);
10565            }
10566        }
10567
10568        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10569        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10570        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10571
10572        // Copy the derived override back to the parsed package, so that we can
10573        // update the package settings accordingly.
10574        pkg.cpuAbiOverride = cpuAbiOverride;
10575
10576        if (DEBUG_ABI_SELECTION) {
10577            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10578                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10579                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10580        }
10581
10582        // Push the derived path down into PackageSettings so we know what to
10583        // clean up at uninstall time.
10584        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10585
10586        if (DEBUG_ABI_SELECTION) {
10587            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10588                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10589                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10590        }
10591
10592        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10593            // We don't do this here during boot because we can do it all
10594            // at once after scanning all existing packages.
10595            //
10596            // We also do this *before* we perform dexopt on this package, so that
10597            // we can avoid redundant dexopts, and also to make sure we've got the
10598            // code and package path correct.
10599            changedAbiCodePath =
10600                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10601        }
10602
10603        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10604                android.Manifest.permission.FACTORY_TEST)) {
10605            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10606        }
10607
10608        if (isSystemApp(pkg)) {
10609            pkgSetting.isOrphaned = true;
10610        }
10611
10612        // Take care of first install / last update times.
10613        final long scanFileTime = getLastModifiedTime(pkg);
10614        if (currentTime != 0) {
10615            if (pkgSetting.firstInstallTime == 0) {
10616                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10617            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10618                pkgSetting.lastUpdateTime = currentTime;
10619            }
10620        } else if (pkgSetting.firstInstallTime == 0) {
10621            // We need *something*.  Take time time stamp of the file.
10622            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10623        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10624            if (scanFileTime != pkgSetting.timeStamp) {
10625                // A package on the system image has changed; consider this
10626                // to be an update.
10627                pkgSetting.lastUpdateTime = scanFileTime;
10628            }
10629        }
10630        pkgSetting.setTimeStamp(scanFileTime);
10631
10632        pkgSetting.pkg = pkg;
10633        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10634        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10635            pkgSetting.versionCode = pkg.getLongVersionCode();
10636        }
10637        // Update volume if needed
10638        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10639        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10640            Slog.i(PackageManagerService.TAG,
10641                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10642                    + " package " + pkg.packageName
10643                    + " volume from " + pkgSetting.volumeUuid
10644                    + " to " + volumeUuid);
10645            pkgSetting.volumeUuid = volumeUuid;
10646        }
10647
10648        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10649    }
10650
10651    /**
10652     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10653     */
10654    private static boolean apkHasCode(String fileName) {
10655        StrictJarFile jarFile = null;
10656        try {
10657            jarFile = new StrictJarFile(fileName,
10658                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10659            return jarFile.findEntry("classes.dex") != null;
10660        } catch (IOException ignore) {
10661        } finally {
10662            try {
10663                if (jarFile != null) {
10664                    jarFile.close();
10665                }
10666            } catch (IOException ignore) {}
10667        }
10668        return false;
10669    }
10670
10671    /**
10672     * Enforces code policy for the package. This ensures that if an APK has
10673     * declared hasCode="true" in its manifest that the APK actually contains
10674     * code.
10675     *
10676     * @throws PackageManagerException If bytecode could not be found when it should exist
10677     */
10678    private static void assertCodePolicy(PackageParser.Package pkg)
10679            throws PackageManagerException {
10680        final boolean shouldHaveCode =
10681                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10682        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10683            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10684                    "Package " + pkg.baseCodePath + " code is missing");
10685        }
10686
10687        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10688            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10689                final boolean splitShouldHaveCode =
10690                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10691                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10692                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10693                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10694                }
10695            }
10696        }
10697    }
10698
10699    /**
10700     * Applies policy to the parsed package based upon the given policy flags.
10701     * Ensures the package is in a good state.
10702     * <p>
10703     * Implementation detail: This method must NOT have any side effect. It would
10704     * ideally be static, but, it requires locks to read system state.
10705     */
10706    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10707            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10708        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10709            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10710            if (pkg.applicationInfo.isDirectBootAware()) {
10711                // we're direct boot aware; set for all components
10712                for (PackageParser.Service s : pkg.services) {
10713                    s.info.encryptionAware = s.info.directBootAware = true;
10714                }
10715                for (PackageParser.Provider p : pkg.providers) {
10716                    p.info.encryptionAware = p.info.directBootAware = true;
10717                }
10718                for (PackageParser.Activity a : pkg.activities) {
10719                    a.info.encryptionAware = a.info.directBootAware = true;
10720                }
10721                for (PackageParser.Activity r : pkg.receivers) {
10722                    r.info.encryptionAware = r.info.directBootAware = true;
10723                }
10724            }
10725            if (compressedFileExists(pkg.codePath)) {
10726                pkg.isStub = true;
10727            }
10728        } else {
10729            // non system apps can't be flagged as core
10730            pkg.coreApp = false;
10731            // clear flags not applicable to regular apps
10732            pkg.applicationInfo.flags &=
10733                    ~ApplicationInfo.FLAG_PERSISTENT;
10734            pkg.applicationInfo.privateFlags &=
10735                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10736            pkg.applicationInfo.privateFlags &=
10737                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10738            // cap permission priorities
10739            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10740                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10741                    pkg.permissionGroups.get(i).info.priority = 0;
10742                }
10743            }
10744        }
10745        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10746            // clear protected broadcasts
10747            pkg.protectedBroadcasts = null;
10748            // ignore export request for single user receivers
10749            if (pkg.receivers != null) {
10750                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10751                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10752                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10753                        receiver.info.exported = false;
10754                    }
10755                }
10756            }
10757            // ignore export request for single user services
10758            if (pkg.services != null) {
10759                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10760                    final PackageParser.Service service = pkg.services.get(i);
10761                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10762                        service.info.exported = false;
10763                    }
10764                }
10765            }
10766            // ignore export request for single user providers
10767            if (pkg.providers != null) {
10768                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10769                    final PackageParser.Provider provider = pkg.providers.get(i);
10770                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10771                        provider.info.exported = false;
10772                    }
10773                }
10774            }
10775        }
10776
10777        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10778            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10779        }
10780
10781        if ((scanFlags & SCAN_AS_OEM) != 0) {
10782            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10783        }
10784
10785        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10786            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10787        }
10788
10789        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10790            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10791        }
10792
10793        // Check if the package is signed with the same key as the platform package.
10794        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10795                (platformPkg != null && compareSignatures(
10796                        platformPkg.mSigningDetails.signatures,
10797                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10798            pkg.applicationInfo.privateFlags |=
10799                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10800        }
10801
10802        if (!isSystemApp(pkg)) {
10803            // Only system apps can use these features.
10804            pkg.mOriginalPackages = null;
10805            pkg.mRealPackage = null;
10806            pkg.mAdoptPermissions = null;
10807        }
10808    }
10809
10810    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10811            throws PackageManagerException {
10812        if (object == null) {
10813            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10814        }
10815        return object;
10816    }
10817
10818    /**
10819     * Asserts the parsed package is valid according to the given policy. If the
10820     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10821     * <p>
10822     * Implementation detail: This method must NOT have any side effects. It would
10823     * ideally be static, but, it requires locks to read system state.
10824     *
10825     * @throws PackageManagerException If the package fails any of the validation checks
10826     */
10827    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10828            final @ScanFlags int scanFlags)
10829                    throws PackageManagerException {
10830        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10831            assertCodePolicy(pkg);
10832        }
10833
10834        if (pkg.applicationInfo.getCodePath() == null ||
10835                pkg.applicationInfo.getResourcePath() == null) {
10836            // Bail out. The resource and code paths haven't been set.
10837            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10838                    "Code and resource paths haven't been set correctly");
10839        }
10840
10841        // Make sure we're not adding any bogus keyset info
10842        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10843        ksms.assertScannedPackageValid(pkg);
10844
10845        synchronized (mPackages) {
10846            // The special "android" package can only be defined once
10847            if (pkg.packageName.equals("android")) {
10848                if (mAndroidApplication != null) {
10849                    Slog.w(TAG, "*************************************************");
10850                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10851                    Slog.w(TAG, " codePath=" + pkg.codePath);
10852                    Slog.w(TAG, "*************************************************");
10853                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10854                            "Core android package being redefined.  Skipping.");
10855                }
10856            }
10857
10858            // A package name must be unique; don't allow duplicates
10859            if (mPackages.containsKey(pkg.packageName)) {
10860                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10861                        "Application package " + pkg.packageName
10862                        + " already installed.  Skipping duplicate.");
10863            }
10864
10865            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10866                // Static libs have a synthetic package name containing the version
10867                // but we still want the base name to be unique.
10868                if (mPackages.containsKey(pkg.manifestPackageName)) {
10869                    throw new PackageManagerException(
10870                            "Duplicate static shared lib provider package");
10871                }
10872
10873                // Static shared libraries should have at least O target SDK
10874                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10875                    throw new PackageManagerException(
10876                            "Packages declaring static-shared libs must target O SDK or higher");
10877                }
10878
10879                // Package declaring static a shared lib cannot be instant apps
10880                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10881                    throw new PackageManagerException(
10882                            "Packages declaring static-shared libs cannot be instant apps");
10883                }
10884
10885                // Package declaring static a shared lib cannot be renamed since the package
10886                // name is synthetic and apps can't code around package manager internals.
10887                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10888                    throw new PackageManagerException(
10889                            "Packages declaring static-shared libs cannot be renamed");
10890                }
10891
10892                // Package declaring static a shared lib cannot declare child packages
10893                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10894                    throw new PackageManagerException(
10895                            "Packages declaring static-shared libs cannot have child packages");
10896                }
10897
10898                // Package declaring static a shared lib cannot declare dynamic libs
10899                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10900                    throw new PackageManagerException(
10901                            "Packages declaring static-shared libs cannot declare dynamic libs");
10902                }
10903
10904                // Package declaring static a shared lib cannot declare shared users
10905                if (pkg.mSharedUserId != null) {
10906                    throw new PackageManagerException(
10907                            "Packages declaring static-shared libs cannot declare shared users");
10908                }
10909
10910                // Static shared libs cannot declare activities
10911                if (!pkg.activities.isEmpty()) {
10912                    throw new PackageManagerException(
10913                            "Static shared libs cannot declare activities");
10914                }
10915
10916                // Static shared libs cannot declare services
10917                if (!pkg.services.isEmpty()) {
10918                    throw new PackageManagerException(
10919                            "Static shared libs cannot declare services");
10920                }
10921
10922                // Static shared libs cannot declare providers
10923                if (!pkg.providers.isEmpty()) {
10924                    throw new PackageManagerException(
10925                            "Static shared libs cannot declare content providers");
10926                }
10927
10928                // Static shared libs cannot declare receivers
10929                if (!pkg.receivers.isEmpty()) {
10930                    throw new PackageManagerException(
10931                            "Static shared libs cannot declare broadcast receivers");
10932                }
10933
10934                // Static shared libs cannot declare permission groups
10935                if (!pkg.permissionGroups.isEmpty()) {
10936                    throw new PackageManagerException(
10937                            "Static shared libs cannot declare permission groups");
10938                }
10939
10940                // Static shared libs cannot declare permissions
10941                if (!pkg.permissions.isEmpty()) {
10942                    throw new PackageManagerException(
10943                            "Static shared libs cannot declare permissions");
10944                }
10945
10946                // Static shared libs cannot declare protected broadcasts
10947                if (pkg.protectedBroadcasts != null) {
10948                    throw new PackageManagerException(
10949                            "Static shared libs cannot declare protected broadcasts");
10950                }
10951
10952                // Static shared libs cannot be overlay targets
10953                if (pkg.mOverlayTarget != null) {
10954                    throw new PackageManagerException(
10955                            "Static shared libs cannot be overlay targets");
10956                }
10957
10958                // The version codes must be ordered as lib versions
10959                long minVersionCode = Long.MIN_VALUE;
10960                long maxVersionCode = Long.MAX_VALUE;
10961
10962                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10963                        pkg.staticSharedLibName);
10964                if (versionedLib != null) {
10965                    final int versionCount = versionedLib.size();
10966                    for (int i = 0; i < versionCount; i++) {
10967                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10968                        final long libVersionCode = libInfo.getDeclaringPackage()
10969                                .getLongVersionCode();
10970                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10971                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10972                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10973                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10974                        } else {
10975                            minVersionCode = maxVersionCode = libVersionCode;
10976                            break;
10977                        }
10978                    }
10979                }
10980                if (pkg.getLongVersionCode() < minVersionCode
10981                        || pkg.getLongVersionCode() > maxVersionCode) {
10982                    throw new PackageManagerException("Static shared"
10983                            + " lib version codes must be ordered as lib versions");
10984                }
10985            }
10986
10987            // Only privileged apps and updated privileged apps can add child packages.
10988            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10989                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10990                    throw new PackageManagerException("Only privileged apps can add child "
10991                            + "packages. Ignoring package " + pkg.packageName);
10992                }
10993                final int childCount = pkg.childPackages.size();
10994                for (int i = 0; i < childCount; i++) {
10995                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10996                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10997                            childPkg.packageName)) {
10998                        throw new PackageManagerException("Can't override child of "
10999                                + "another disabled app. Ignoring package " + pkg.packageName);
11000                    }
11001                }
11002            }
11003
11004            // If we're only installing presumed-existing packages, require that the
11005            // scanned APK is both already known and at the path previously established
11006            // for it.  Previously unknown packages we pick up normally, but if we have an
11007            // a priori expectation about this package's install presence, enforce it.
11008            // With a singular exception for new system packages. When an OTA contains
11009            // a new system package, we allow the codepath to change from a system location
11010            // to the user-installed location. If we don't allow this change, any newer,
11011            // user-installed version of the application will be ignored.
11012            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11013                if (mExpectingBetter.containsKey(pkg.packageName)) {
11014                    logCriticalInfo(Log.WARN,
11015                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11016                } else {
11017                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11018                    if (known != null) {
11019                        if (DEBUG_PACKAGE_SCANNING) {
11020                            Log.d(TAG, "Examining " + pkg.codePath
11021                                    + " and requiring known paths " + known.codePathString
11022                                    + " & " + known.resourcePathString);
11023                        }
11024                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11025                                || !pkg.applicationInfo.getResourcePath().equals(
11026                                        known.resourcePathString)) {
11027                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11028                                    "Application package " + pkg.packageName
11029                                    + " found at " + pkg.applicationInfo.getCodePath()
11030                                    + " but expected at " + known.codePathString
11031                                    + "; ignoring.");
11032                        }
11033                    } else {
11034                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11035                                "Application package " + pkg.packageName
11036                                + " not found; ignoring.");
11037                    }
11038                }
11039            }
11040
11041            // Verify that this new package doesn't have any content providers
11042            // that conflict with existing packages.  Only do this if the
11043            // package isn't already installed, since we don't want to break
11044            // things that are installed.
11045            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11046                final int N = pkg.providers.size();
11047                int i;
11048                for (i=0; i<N; i++) {
11049                    PackageParser.Provider p = pkg.providers.get(i);
11050                    if (p.info.authority != null) {
11051                        String names[] = p.info.authority.split(";");
11052                        for (int j = 0; j < names.length; j++) {
11053                            if (mProvidersByAuthority.containsKey(names[j])) {
11054                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11055                                final String otherPackageName =
11056                                        ((other != null && other.getComponentName() != null) ?
11057                                                other.getComponentName().getPackageName() : "?");
11058                                throw new PackageManagerException(
11059                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11060                                        "Can't install because provider name " + names[j]
11061                                                + " (in package " + pkg.applicationInfo.packageName
11062                                                + ") is already used by " + otherPackageName);
11063                            }
11064                        }
11065                    }
11066                }
11067            }
11068
11069            // Verify that packages sharing a user with a privileged app are marked as privileged.
11070            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11071                SharedUserSetting sharedUserSetting = null;
11072                try {
11073                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11074                } catch (PackageManagerException ignore) {}
11075                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11076                    // Exempt SharedUsers signed with the platform key.
11077                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11078                    if ((platformPkgSetting.signatures.mSigningDetails
11079                            != PackageParser.SigningDetails.UNKNOWN)
11080                            && (compareSignatures(
11081                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11082                                    pkg.mSigningDetails.signatures)
11083                                            != PackageManager.SIGNATURE_MATCH)) {
11084                        throw new PackageManagerException("Apps that share a user with a " +
11085                                "privileged app must themselves be marked as privileged. " +
11086                                pkg.packageName + " shares privileged user " +
11087                                pkg.mSharedUserId + ".");
11088                    }
11089                }
11090            }
11091
11092            // Apply policies specific for runtime resource overlays (RROs).
11093            if (pkg.mOverlayTarget != null) {
11094                // System overlays have some restrictions on their use of the 'static' state.
11095                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11096                    // We are scanning a system overlay. This can be the first scan of the
11097                    // system/vendor/oem partition, or an update to the system overlay.
11098                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11099                        // This must be an update to a system overlay.
11100                        final PackageSetting previousPkg = assertNotNull(
11101                                mSettings.getPackageLPr(pkg.packageName),
11102                                "previous package state not present");
11103
11104                        // Static overlays cannot be updated.
11105                        if (previousPkg.pkg.mOverlayIsStatic) {
11106                            throw new PackageManagerException("Overlay " + pkg.packageName +
11107                                    " is static and cannot be upgraded.");
11108                        // Non-static overlays cannot be converted to static overlays.
11109                        } else if (pkg.mOverlayIsStatic) {
11110                            throw new PackageManagerException("Overlay " + pkg.packageName +
11111                                    " cannot be upgraded into a static overlay.");
11112                        }
11113                    }
11114                } else {
11115                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11116                    if (pkg.mOverlayIsStatic) {
11117                        throw new PackageManagerException("Overlay " + pkg.packageName +
11118                                " is static but not pre-installed.");
11119                    }
11120
11121                    // The only case where we allow installation of a non-system overlay is when
11122                    // its signature is signed with the platform certificate.
11123                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11124                    if ((platformPkgSetting.signatures.mSigningDetails
11125                            != PackageParser.SigningDetails.UNKNOWN)
11126                            && (compareSignatures(
11127                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11128                                    pkg.mSigningDetails.signatures)
11129                                            != PackageManager.SIGNATURE_MATCH)) {
11130                        throw new PackageManagerException("Overlay " + pkg.packageName +
11131                                " must be signed with the platform certificate.");
11132                    }
11133                }
11134            }
11135        }
11136    }
11137
11138    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11139            int type, String declaringPackageName, long declaringVersionCode) {
11140        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11141        if (versionedLib == null) {
11142            versionedLib = new LongSparseArray<>();
11143            mSharedLibraries.put(name, versionedLib);
11144            if (type == SharedLibraryInfo.TYPE_STATIC) {
11145                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11146            }
11147        } else if (versionedLib.indexOfKey(version) >= 0) {
11148            return false;
11149        }
11150        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11151                version, type, declaringPackageName, declaringVersionCode);
11152        versionedLib.put(version, libEntry);
11153        return true;
11154    }
11155
11156    private boolean removeSharedLibraryLPw(String name, long version) {
11157        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11158        if (versionedLib == null) {
11159            return false;
11160        }
11161        final int libIdx = versionedLib.indexOfKey(version);
11162        if (libIdx < 0) {
11163            return false;
11164        }
11165        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11166        versionedLib.remove(version);
11167        if (versionedLib.size() <= 0) {
11168            mSharedLibraries.remove(name);
11169            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11170                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11171                        .getPackageName());
11172            }
11173        }
11174        return true;
11175    }
11176
11177    /**
11178     * Adds a scanned package to the system. When this method is finished, the package will
11179     * be available for query, resolution, etc...
11180     */
11181    private void commitPackageSettings(PackageParser.Package pkg,
11182            @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, UserHandle user,
11183            final @ScanFlags int scanFlags, boolean chatty) {
11184        final String pkgName = pkg.packageName;
11185        if (mCustomResolverComponentName != null &&
11186                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11187            setUpCustomResolverActivity(pkg);
11188        }
11189
11190        if (pkg.packageName.equals("android")) {
11191            synchronized (mPackages) {
11192                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11193                    // Set up information for our fall-back user intent resolution activity.
11194                    mPlatformPackage = pkg;
11195                    pkg.mVersionCode = mSdkVersion;
11196                    pkg.mVersionCodeMajor = 0;
11197                    mAndroidApplication = pkg.applicationInfo;
11198                    if (!mResolverReplaced) {
11199                        mResolveActivity.applicationInfo = mAndroidApplication;
11200                        mResolveActivity.name = ResolverActivity.class.getName();
11201                        mResolveActivity.packageName = mAndroidApplication.packageName;
11202                        mResolveActivity.processName = "system:ui";
11203                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11204                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11205                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11206                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11207                        mResolveActivity.exported = true;
11208                        mResolveActivity.enabled = true;
11209                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11210                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11211                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11212                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11213                                | ActivityInfo.CONFIG_ORIENTATION
11214                                | ActivityInfo.CONFIG_KEYBOARD
11215                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11216                        mResolveInfo.activityInfo = mResolveActivity;
11217                        mResolveInfo.priority = 0;
11218                        mResolveInfo.preferredOrder = 0;
11219                        mResolveInfo.match = 0;
11220                        mResolveComponentName = new ComponentName(
11221                                mAndroidApplication.packageName, mResolveActivity.name);
11222                    }
11223                }
11224            }
11225        }
11226
11227        ArrayList<PackageParser.Package> clientLibPkgs = null;
11228        // writer
11229        synchronized (mPackages) {
11230            boolean hasStaticSharedLibs = false;
11231
11232            // Any app can add new static shared libraries
11233            if (pkg.staticSharedLibName != null) {
11234                // Static shared libs don't allow renaming as they have synthetic package
11235                // names to allow install of multiple versions, so use name from manifest.
11236                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11237                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11238                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11239                    hasStaticSharedLibs = true;
11240                } else {
11241                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11242                                + pkg.staticSharedLibName + " already exists; skipping");
11243                }
11244                // Static shared libs cannot be updated once installed since they
11245                // use synthetic package name which includes the version code, so
11246                // not need to update other packages's shared lib dependencies.
11247            }
11248
11249            if (!hasStaticSharedLibs
11250                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11251                // Only system apps can add new dynamic shared libraries.
11252                if (pkg.libraryNames != null) {
11253                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11254                        String name = pkg.libraryNames.get(i);
11255                        boolean allowed = false;
11256                        if (pkg.isUpdatedSystemApp()) {
11257                            // New library entries can only be added through the
11258                            // system image.  This is important to get rid of a lot
11259                            // of nasty edge cases: for example if we allowed a non-
11260                            // system update of the app to add a library, then uninstalling
11261                            // the update would make the library go away, and assumptions
11262                            // we made such as through app install filtering would now
11263                            // have allowed apps on the device which aren't compatible
11264                            // with it.  Better to just have the restriction here, be
11265                            // conservative, and create many fewer cases that can negatively
11266                            // impact the user experience.
11267                            final PackageSetting sysPs = mSettings
11268                                    .getDisabledSystemPkgLPr(pkg.packageName);
11269                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11270                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11271                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11272                                        allowed = true;
11273                                        break;
11274                                    }
11275                                }
11276                            }
11277                        } else {
11278                            allowed = true;
11279                        }
11280                        if (allowed) {
11281                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11282                                    SharedLibraryInfo.VERSION_UNDEFINED,
11283                                    SharedLibraryInfo.TYPE_DYNAMIC,
11284                                    pkg.packageName, pkg.getLongVersionCode())) {
11285                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11286                                        + name + " already exists; skipping");
11287                            }
11288                        } else {
11289                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11290                                    + name + " that is not declared on system image; skipping");
11291                        }
11292                    }
11293
11294                    if ((scanFlags & SCAN_BOOTING) == 0) {
11295                        // If we are not booting, we need to update any applications
11296                        // that are clients of our shared library.  If we are booting,
11297                        // this will all be done once the scan is complete.
11298                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11299                    }
11300                }
11301            }
11302        }
11303
11304        if ((scanFlags & SCAN_BOOTING) != 0) {
11305            // No apps can run during boot scan, so they don't need to be frozen
11306        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11307            // Caller asked to not kill app, so it's probably not frozen
11308        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11309            // Caller asked us to ignore frozen check for some reason; they
11310            // probably didn't know the package name
11311        } else {
11312            // We're doing major surgery on this package, so it better be frozen
11313            // right now to keep it from launching
11314            checkPackageFrozen(pkgName);
11315        }
11316
11317        // Also need to kill any apps that are dependent on the library.
11318        if (clientLibPkgs != null) {
11319            for (int i=0; i<clientLibPkgs.size(); i++) {
11320                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11321                killApplication(clientPkg.applicationInfo.packageName,
11322                        clientPkg.applicationInfo.uid, "update lib");
11323            }
11324        }
11325
11326        // writer
11327        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11328
11329        synchronized (mPackages) {
11330            // We don't expect installation to fail beyond this point
11331
11332            // Add the new setting to mSettings
11333            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11334            // Add the new setting to mPackages
11335            mPackages.put(pkg.applicationInfo.packageName, pkg);
11336            // Make sure we don't accidentally delete its data.
11337            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11338            while (iter.hasNext()) {
11339                PackageCleanItem item = iter.next();
11340                if (pkgName.equals(item.packageName)) {
11341                    iter.remove();
11342                }
11343            }
11344
11345            // Add the package's KeySets to the global KeySetManagerService
11346            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11347            ksms.addScannedPackageLPw(pkg);
11348
11349            int N = pkg.providers.size();
11350            StringBuilder r = null;
11351            int i;
11352            for (i=0; i<N; i++) {
11353                PackageParser.Provider p = pkg.providers.get(i);
11354                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11355                        p.info.processName);
11356                mProviders.addProvider(p);
11357                p.syncable = p.info.isSyncable;
11358                if (p.info.authority != null) {
11359                    String names[] = p.info.authority.split(";");
11360                    p.info.authority = null;
11361                    for (int j = 0; j < names.length; j++) {
11362                        if (j == 1 && p.syncable) {
11363                            // We only want the first authority for a provider to possibly be
11364                            // syncable, so if we already added this provider using a different
11365                            // authority clear the syncable flag. We copy the provider before
11366                            // changing it because the mProviders object contains a reference
11367                            // to a provider that we don't want to change.
11368                            // Only do this for the second authority since the resulting provider
11369                            // object can be the same for all future authorities for this provider.
11370                            p = new PackageParser.Provider(p);
11371                            p.syncable = false;
11372                        }
11373                        if (!mProvidersByAuthority.containsKey(names[j])) {
11374                            mProvidersByAuthority.put(names[j], p);
11375                            if (p.info.authority == null) {
11376                                p.info.authority = names[j];
11377                            } else {
11378                                p.info.authority = p.info.authority + ";" + names[j];
11379                            }
11380                            if (DEBUG_PACKAGE_SCANNING) {
11381                                if (chatty)
11382                                    Log.d(TAG, "Registered content provider: " + names[j]
11383                                            + ", className = " + p.info.name + ", isSyncable = "
11384                                            + p.info.isSyncable);
11385                            }
11386                        } else {
11387                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11388                            Slog.w(TAG, "Skipping provider name " + names[j] +
11389                                    " (in package " + pkg.applicationInfo.packageName +
11390                                    "): name already used by "
11391                                    + ((other != null && other.getComponentName() != null)
11392                                            ? other.getComponentName().getPackageName() : "?"));
11393                        }
11394                    }
11395                }
11396                if (chatty) {
11397                    if (r == null) {
11398                        r = new StringBuilder(256);
11399                    } else {
11400                        r.append(' ');
11401                    }
11402                    r.append(p.info.name);
11403                }
11404            }
11405            if (r != null) {
11406                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11407            }
11408
11409            N = pkg.services.size();
11410            r = null;
11411            for (i=0; i<N; i++) {
11412                PackageParser.Service s = pkg.services.get(i);
11413                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11414                        s.info.processName);
11415                mServices.addService(s);
11416                if (chatty) {
11417                    if (r == null) {
11418                        r = new StringBuilder(256);
11419                    } else {
11420                        r.append(' ');
11421                    }
11422                    r.append(s.info.name);
11423                }
11424            }
11425            if (r != null) {
11426                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11427            }
11428
11429            N = pkg.receivers.size();
11430            r = null;
11431            for (i=0; i<N; i++) {
11432                PackageParser.Activity a = pkg.receivers.get(i);
11433                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11434                        a.info.processName);
11435                mReceivers.addActivity(a, "receiver");
11436                if (chatty) {
11437                    if (r == null) {
11438                        r = new StringBuilder(256);
11439                    } else {
11440                        r.append(' ');
11441                    }
11442                    r.append(a.info.name);
11443                }
11444            }
11445            if (r != null) {
11446                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11447            }
11448
11449            N = pkg.activities.size();
11450            r = null;
11451            for (i=0; i<N; i++) {
11452                PackageParser.Activity a = pkg.activities.get(i);
11453                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11454                        a.info.processName);
11455                mActivities.addActivity(a, "activity");
11456                if (chatty) {
11457                    if (r == null) {
11458                        r = new StringBuilder(256);
11459                    } else {
11460                        r.append(' ');
11461                    }
11462                    r.append(a.info.name);
11463                }
11464            }
11465            if (r != null) {
11466                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11467            }
11468
11469            // Don't allow ephemeral applications to define new permissions groups.
11470            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11471                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11472                        + " ignored: instant apps cannot define new permission groups.");
11473            } else {
11474                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11475            }
11476
11477            // Don't allow ephemeral applications to define new permissions.
11478            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11479                Slog.w(TAG, "Permissions from package " + pkg.packageName
11480                        + " ignored: instant apps cannot define new permissions.");
11481            } else {
11482                mPermissionManager.addAllPermissions(pkg, chatty);
11483            }
11484
11485            N = pkg.instrumentation.size();
11486            r = null;
11487            for (i=0; i<N; i++) {
11488                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11489                a.info.packageName = pkg.applicationInfo.packageName;
11490                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11491                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11492                a.info.splitNames = pkg.splitNames;
11493                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11494                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11495                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11496                a.info.dataDir = pkg.applicationInfo.dataDir;
11497                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11498                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11499                a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11500                a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
11501                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11502                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11503                mInstrumentation.put(a.getComponentName(), a);
11504                if (chatty) {
11505                    if (r == null) {
11506                        r = new StringBuilder(256);
11507                    } else {
11508                        r.append(' ');
11509                    }
11510                    r.append(a.info.name);
11511                }
11512            }
11513            if (r != null) {
11514                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11515            }
11516
11517            if (pkg.protectedBroadcasts != null) {
11518                N = pkg.protectedBroadcasts.size();
11519                synchronized (mProtectedBroadcasts) {
11520                    for (i = 0; i < N; i++) {
11521                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11522                    }
11523                }
11524            }
11525
11526            if (oldPkg != null) {
11527                // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
11528                // revoke callbacks from this method might need to kill apps which need the
11529                // mPackages lock on a different thread. This would dead lock.
11530                //
11531                // Hence create a copy of all package names and pass it into
11532                // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
11533                // revoked. If a new package is added before the async code runs the permission
11534                // won't be granted yet, hence new packages are no problem.
11535                final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
11536
11537                AsyncTask.execute(() ->
11538                        mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
11539                                allPackageNames, mPermissionCallback));
11540            }
11541        }
11542
11543        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11544    }
11545
11546    /**
11547     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11548     * is derived purely on the basis of the contents of {@code scanFile} and
11549     * {@code cpuAbiOverride}.
11550     *
11551     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11552     */
11553    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11554            boolean extractLibs)
11555                    throws PackageManagerException {
11556        // Give ourselves some initial paths; we'll come back for another
11557        // pass once we've determined ABI below.
11558        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11559
11560        // We would never need to extract libs for forward-locked and external packages,
11561        // since the container service will do it for us. We shouldn't attempt to
11562        // extract libs from system app when it was not updated.
11563        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11564                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11565            extractLibs = false;
11566        }
11567
11568        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11569        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11570
11571        NativeLibraryHelper.Handle handle = null;
11572        try {
11573            handle = NativeLibraryHelper.Handle.create(pkg);
11574            // TODO(multiArch): This can be null for apps that didn't go through the
11575            // usual installation process. We can calculate it again, like we
11576            // do during install time.
11577            //
11578            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11579            // unnecessary.
11580            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11581
11582            // Null out the abis so that they can be recalculated.
11583            pkg.applicationInfo.primaryCpuAbi = null;
11584            pkg.applicationInfo.secondaryCpuAbi = null;
11585            if (isMultiArch(pkg.applicationInfo)) {
11586                // Warn if we've set an abiOverride for multi-lib packages..
11587                // By definition, we need to copy both 32 and 64 bit libraries for
11588                // such packages.
11589                if (pkg.cpuAbiOverride != null
11590                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11591                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11592                }
11593
11594                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11595                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11596                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11597                    if (extractLibs) {
11598                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11599                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11600                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11601                                useIsaSpecificSubdirs);
11602                    } else {
11603                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11604                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11605                    }
11606                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11607                }
11608
11609                // Shared library native code should be in the APK zip aligned
11610                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11611                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11612                            "Shared library native lib extraction not supported");
11613                }
11614
11615                maybeThrowExceptionForMultiArchCopy(
11616                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11617
11618                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11619                    if (extractLibs) {
11620                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11621                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11622                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11623                                useIsaSpecificSubdirs);
11624                    } else {
11625                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11626                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11627                    }
11628                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11629                }
11630
11631                maybeThrowExceptionForMultiArchCopy(
11632                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11633
11634                if (abi64 >= 0) {
11635                    // Shared library native libs should be in the APK zip aligned
11636                    if (extractLibs && pkg.isLibrary()) {
11637                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11638                                "Shared library native lib extraction not supported");
11639                    }
11640                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11641                }
11642
11643                if (abi32 >= 0) {
11644                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11645                    if (abi64 >= 0) {
11646                        if (pkg.use32bitAbi) {
11647                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11648                            pkg.applicationInfo.primaryCpuAbi = abi;
11649                        } else {
11650                            pkg.applicationInfo.secondaryCpuAbi = abi;
11651                        }
11652                    } else {
11653                        pkg.applicationInfo.primaryCpuAbi = abi;
11654                    }
11655                }
11656            } else {
11657                String[] abiList = (cpuAbiOverride != null) ?
11658                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11659
11660                // Enable gross and lame hacks for apps that are built with old
11661                // SDK tools. We must scan their APKs for renderscript bitcode and
11662                // not launch them if it's present. Don't bother checking on devices
11663                // that don't have 64 bit support.
11664                boolean needsRenderScriptOverride = false;
11665                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11666                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11667                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11668                    needsRenderScriptOverride = true;
11669                }
11670
11671                final int copyRet;
11672                if (extractLibs) {
11673                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11674                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11675                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11676                } else {
11677                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11678                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11679                }
11680                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11681
11682                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11683                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11684                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11685                }
11686
11687                if (copyRet >= 0) {
11688                    // Shared libraries that have native libs must be multi-architecture
11689                    if (pkg.isLibrary()) {
11690                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11691                                "Shared library with native libs must be multiarch");
11692                    }
11693                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11694                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11695                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11696                } else if (needsRenderScriptOverride) {
11697                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11698                }
11699            }
11700        } catch (IOException ioe) {
11701            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11702        } finally {
11703            IoUtils.closeQuietly(handle);
11704        }
11705
11706        // Now that we've calculated the ABIs and determined if it's an internal app,
11707        // we will go ahead and populate the nativeLibraryPath.
11708        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11709    }
11710
11711    /**
11712     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11713     * i.e, so that all packages can be run inside a single process if required.
11714     *
11715     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11716     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11717     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11718     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11719     * updating a package that belongs to a shared user.
11720     *
11721     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11722     * adds unnecessary complexity.
11723     */
11724    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11725            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11726        List<String> changedAbiCodePath = null;
11727        String requiredInstructionSet = null;
11728        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11729            requiredInstructionSet = VMRuntime.getInstructionSet(
11730                     scannedPackage.applicationInfo.primaryCpuAbi);
11731        }
11732
11733        PackageSetting requirer = null;
11734        for (PackageSetting ps : packagesForUser) {
11735            // If packagesForUser contains scannedPackage, we skip it. This will happen
11736            // when scannedPackage is an update of an existing package. Without this check,
11737            // we will never be able to change the ABI of any package belonging to a shared
11738            // user, even if it's compatible with other packages.
11739            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11740                if (ps.primaryCpuAbiString == null) {
11741                    continue;
11742                }
11743
11744                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11745                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11746                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11747                    // this but there's not much we can do.
11748                    String errorMessage = "Instruction set mismatch, "
11749                            + ((requirer == null) ? "[caller]" : requirer)
11750                            + " requires " + requiredInstructionSet + " whereas " + ps
11751                            + " requires " + instructionSet;
11752                    Slog.w(TAG, errorMessage);
11753                }
11754
11755                if (requiredInstructionSet == null) {
11756                    requiredInstructionSet = instructionSet;
11757                    requirer = ps;
11758                }
11759            }
11760        }
11761
11762        if (requiredInstructionSet != null) {
11763            String adjustedAbi;
11764            if (requirer != null) {
11765                // requirer != null implies that either scannedPackage was null or that scannedPackage
11766                // did not require an ABI, in which case we have to adjust scannedPackage to match
11767                // the ABI of the set (which is the same as requirer's ABI)
11768                adjustedAbi = requirer.primaryCpuAbiString;
11769                if (scannedPackage != null) {
11770                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11771                }
11772            } else {
11773                // requirer == null implies that we're updating all ABIs in the set to
11774                // match scannedPackage.
11775                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11776            }
11777
11778            for (PackageSetting ps : packagesForUser) {
11779                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11780                    if (ps.primaryCpuAbiString != null) {
11781                        continue;
11782                    }
11783
11784                    ps.primaryCpuAbiString = adjustedAbi;
11785                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11786                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11787                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11788                        if (DEBUG_ABI_SELECTION) {
11789                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11790                                    + " (requirer="
11791                                    + (requirer != null ? requirer.pkg : "null")
11792                                    + ", scannedPackage="
11793                                    + (scannedPackage != null ? scannedPackage : "null")
11794                                    + ")");
11795                        }
11796                        if (changedAbiCodePath == null) {
11797                            changedAbiCodePath = new ArrayList<>();
11798                        }
11799                        changedAbiCodePath.add(ps.codePathString);
11800                    }
11801                }
11802            }
11803        }
11804        return changedAbiCodePath;
11805    }
11806
11807    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11808        synchronized (mPackages) {
11809            mResolverReplaced = true;
11810            // Set up information for custom user intent resolution activity.
11811            mResolveActivity.applicationInfo = pkg.applicationInfo;
11812            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11813            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11814            mResolveActivity.processName = pkg.applicationInfo.packageName;
11815            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11816            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11817                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11818            mResolveActivity.theme = 0;
11819            mResolveActivity.exported = true;
11820            mResolveActivity.enabled = true;
11821            mResolveInfo.activityInfo = mResolveActivity;
11822            mResolveInfo.priority = 0;
11823            mResolveInfo.preferredOrder = 0;
11824            mResolveInfo.match = 0;
11825            mResolveComponentName = mCustomResolverComponentName;
11826            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11827                    mResolveComponentName);
11828        }
11829    }
11830
11831    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11832        if (installerActivity == null) {
11833            if (DEBUG_INSTANT) {
11834                Slog.d(TAG, "Clear ephemeral installer activity");
11835            }
11836            mInstantAppInstallerActivity = null;
11837            return;
11838        }
11839
11840        if (DEBUG_INSTANT) {
11841            Slog.d(TAG, "Set ephemeral installer activity: "
11842                    + installerActivity.getComponentName());
11843        }
11844        // Set up information for ephemeral installer activity
11845        mInstantAppInstallerActivity = installerActivity;
11846        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11847                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11848        mInstantAppInstallerActivity.exported = true;
11849        mInstantAppInstallerActivity.enabled = true;
11850        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11851        mInstantAppInstallerInfo.priority = 1;
11852        mInstantAppInstallerInfo.preferredOrder = 1;
11853        mInstantAppInstallerInfo.isDefault = true;
11854        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11855                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11856    }
11857
11858    private static String calculateBundledApkRoot(final String codePathString) {
11859        final File codePath = new File(codePathString);
11860        final File codeRoot;
11861        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11862            codeRoot = Environment.getRootDirectory();
11863        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11864            codeRoot = Environment.getOemDirectory();
11865        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11866            codeRoot = Environment.getVendorDirectory();
11867        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11868            codeRoot = Environment.getOdmDirectory();
11869        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11870            codeRoot = Environment.getProductDirectory();
11871        } else {
11872            // Unrecognized code path; take its top real segment as the apk root:
11873            // e.g. /something/app/blah.apk => /something
11874            try {
11875                File f = codePath.getCanonicalFile();
11876                File parent = f.getParentFile();    // non-null because codePath is a file
11877                File tmp;
11878                while ((tmp = parent.getParentFile()) != null) {
11879                    f = parent;
11880                    parent = tmp;
11881                }
11882                codeRoot = f;
11883                Slog.w(TAG, "Unrecognized code path "
11884                        + codePath + " - using " + codeRoot);
11885            } catch (IOException e) {
11886                // Can't canonicalize the code path -- shenanigans?
11887                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11888                return Environment.getRootDirectory().getPath();
11889            }
11890        }
11891        return codeRoot.getPath();
11892    }
11893
11894    /**
11895     * Derive and set the location of native libraries for the given package,
11896     * which varies depending on where and how the package was installed.
11897     */
11898    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11899        final ApplicationInfo info = pkg.applicationInfo;
11900        final String codePath = pkg.codePath;
11901        final File codeFile = new File(codePath);
11902        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11903        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11904
11905        info.nativeLibraryRootDir = null;
11906        info.nativeLibraryRootRequiresIsa = false;
11907        info.nativeLibraryDir = null;
11908        info.secondaryNativeLibraryDir = null;
11909
11910        if (isApkFile(codeFile)) {
11911            // Monolithic install
11912            if (bundledApp) {
11913                // If "/system/lib64/apkname" exists, assume that is the per-package
11914                // native library directory to use; otherwise use "/system/lib/apkname".
11915                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11916                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11917                        getPrimaryInstructionSet(info));
11918
11919                // This is a bundled system app so choose the path based on the ABI.
11920                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11921                // is just the default path.
11922                final String apkName = deriveCodePathName(codePath);
11923                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11924                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11925                        apkName).getAbsolutePath();
11926
11927                if (info.secondaryCpuAbi != null) {
11928                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11929                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11930                            secondaryLibDir, apkName).getAbsolutePath();
11931                }
11932            } else if (asecApp) {
11933                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11934                        .getAbsolutePath();
11935            } else {
11936                final String apkName = deriveCodePathName(codePath);
11937                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11938                        .getAbsolutePath();
11939            }
11940
11941            info.nativeLibraryRootRequiresIsa = false;
11942            info.nativeLibraryDir = info.nativeLibraryRootDir;
11943        } else {
11944            // Cluster install
11945            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11946            info.nativeLibraryRootRequiresIsa = true;
11947
11948            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11949                    getPrimaryInstructionSet(info)).getAbsolutePath();
11950
11951            if (info.secondaryCpuAbi != null) {
11952                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11953                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11954            }
11955        }
11956    }
11957
11958    /**
11959     * Calculate the abis and roots for a bundled app. These can uniquely
11960     * be determined from the contents of the system partition, i.e whether
11961     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11962     * of this information, and instead assume that the system was built
11963     * sensibly.
11964     */
11965    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11966                                           PackageSetting pkgSetting) {
11967        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11968
11969        // If "/system/lib64/apkname" exists, assume that is the per-package
11970        // native library directory to use; otherwise use "/system/lib/apkname".
11971        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11972        setBundledAppAbi(pkg, apkRoot, apkName);
11973        // pkgSetting might be null during rescan following uninstall of updates
11974        // to a bundled app, so accommodate that possibility.  The settings in
11975        // that case will be established later from the parsed package.
11976        //
11977        // If the settings aren't null, sync them up with what we've just derived.
11978        // note that apkRoot isn't stored in the package settings.
11979        if (pkgSetting != null) {
11980            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11981            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11982        }
11983    }
11984
11985    /**
11986     * Deduces the ABI of a bundled app and sets the relevant fields on the
11987     * parsed pkg object.
11988     *
11989     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11990     *        under which system libraries are installed.
11991     * @param apkName the name of the installed package.
11992     */
11993    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11994        final File codeFile = new File(pkg.codePath);
11995
11996        final boolean has64BitLibs;
11997        final boolean has32BitLibs;
11998        if (isApkFile(codeFile)) {
11999            // Monolithic install
12000            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12001            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12002        } else {
12003            // Cluster install
12004            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12005            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12006                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12007                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12008                has64BitLibs = (new File(rootDir, isa)).exists();
12009            } else {
12010                has64BitLibs = false;
12011            }
12012            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12013                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12014                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12015                has32BitLibs = (new File(rootDir, isa)).exists();
12016            } else {
12017                has32BitLibs = false;
12018            }
12019        }
12020
12021        if (has64BitLibs && !has32BitLibs) {
12022            // The package has 64 bit libs, but not 32 bit libs. Its primary
12023            // ABI should be 64 bit. We can safely assume here that the bundled
12024            // native libraries correspond to the most preferred ABI in the list.
12025
12026            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12027            pkg.applicationInfo.secondaryCpuAbi = null;
12028        } else if (has32BitLibs && !has64BitLibs) {
12029            // The package has 32 bit libs but not 64 bit libs. Its primary
12030            // ABI should be 32 bit.
12031
12032            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12033            pkg.applicationInfo.secondaryCpuAbi = null;
12034        } else if (has32BitLibs && has64BitLibs) {
12035            // The application has both 64 and 32 bit bundled libraries. We check
12036            // here that the app declares multiArch support, and warn if it doesn't.
12037            //
12038            // We will be lenient here and record both ABIs. The primary will be the
12039            // ABI that's higher on the list, i.e, a device that's configured to prefer
12040            // 64 bit apps will see a 64 bit primary ABI,
12041
12042            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12043                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12044            }
12045
12046            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12047                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12048                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12049            } else {
12050                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12051                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12052            }
12053        } else {
12054            pkg.applicationInfo.primaryCpuAbi = null;
12055            pkg.applicationInfo.secondaryCpuAbi = null;
12056        }
12057    }
12058
12059    private void killApplication(String pkgName, int appId, String reason) {
12060        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12061    }
12062
12063    private void killApplication(String pkgName, int appId, int userId, String reason) {
12064        // Request the ActivityManager to kill the process(only for existing packages)
12065        // so that we do not end up in a confused state while the user is still using the older
12066        // version of the application while the new one gets installed.
12067        final long token = Binder.clearCallingIdentity();
12068        try {
12069            IActivityManager am = ActivityManager.getService();
12070            if (am != null) {
12071                try {
12072                    am.killApplication(pkgName, appId, userId, reason);
12073                } catch (RemoteException e) {
12074                }
12075            }
12076        } finally {
12077            Binder.restoreCallingIdentity(token);
12078        }
12079    }
12080
12081    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12082        // Remove the parent package setting
12083        PackageSetting ps = (PackageSetting) pkg.mExtras;
12084        if (ps != null) {
12085            removePackageLI(ps, chatty);
12086        }
12087        // Remove the child package setting
12088        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12089        for (int i = 0; i < childCount; i++) {
12090            PackageParser.Package childPkg = pkg.childPackages.get(i);
12091            ps = (PackageSetting) childPkg.mExtras;
12092            if (ps != null) {
12093                removePackageLI(ps, chatty);
12094            }
12095        }
12096    }
12097
12098    void removePackageLI(PackageSetting ps, boolean chatty) {
12099        if (DEBUG_INSTALL) {
12100            if (chatty)
12101                Log.d(TAG, "Removing package " + ps.name);
12102        }
12103
12104        // writer
12105        synchronized (mPackages) {
12106            mPackages.remove(ps.name);
12107            final PackageParser.Package pkg = ps.pkg;
12108            if (pkg != null) {
12109                cleanPackageDataStructuresLILPw(pkg, chatty);
12110            }
12111        }
12112    }
12113
12114    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12115        if (DEBUG_INSTALL) {
12116            if (chatty)
12117                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12118        }
12119
12120        // writer
12121        synchronized (mPackages) {
12122            // Remove the parent package
12123            mPackages.remove(pkg.applicationInfo.packageName);
12124            cleanPackageDataStructuresLILPw(pkg, chatty);
12125
12126            // Remove the child packages
12127            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12128            for (int i = 0; i < childCount; i++) {
12129                PackageParser.Package childPkg = pkg.childPackages.get(i);
12130                mPackages.remove(childPkg.applicationInfo.packageName);
12131                cleanPackageDataStructuresLILPw(childPkg, chatty);
12132            }
12133        }
12134    }
12135
12136    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12137        int N = pkg.providers.size();
12138        StringBuilder r = null;
12139        int i;
12140        for (i=0; i<N; i++) {
12141            PackageParser.Provider p = pkg.providers.get(i);
12142            mProviders.removeProvider(p);
12143            if (p.info.authority == null) {
12144
12145                /* There was another ContentProvider with this authority when
12146                 * this app was installed so this authority is null,
12147                 * Ignore it as we don't have to unregister the provider.
12148                 */
12149                continue;
12150            }
12151            String names[] = p.info.authority.split(";");
12152            for (int j = 0; j < names.length; j++) {
12153                if (mProvidersByAuthority.get(names[j]) == p) {
12154                    mProvidersByAuthority.remove(names[j]);
12155                    if (DEBUG_REMOVE) {
12156                        if (chatty)
12157                            Log.d(TAG, "Unregistered content provider: " + names[j]
12158                                    + ", className = " + p.info.name + ", isSyncable = "
12159                                    + p.info.isSyncable);
12160                    }
12161                }
12162            }
12163            if (DEBUG_REMOVE && chatty) {
12164                if (r == null) {
12165                    r = new StringBuilder(256);
12166                } else {
12167                    r.append(' ');
12168                }
12169                r.append(p.info.name);
12170            }
12171        }
12172        if (r != null) {
12173            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12174        }
12175
12176        N = pkg.services.size();
12177        r = null;
12178        for (i=0; i<N; i++) {
12179            PackageParser.Service s = pkg.services.get(i);
12180            mServices.removeService(s);
12181            if (chatty) {
12182                if (r == null) {
12183                    r = new StringBuilder(256);
12184                } else {
12185                    r.append(' ');
12186                }
12187                r.append(s.info.name);
12188            }
12189        }
12190        if (r != null) {
12191            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12192        }
12193
12194        N = pkg.receivers.size();
12195        r = null;
12196        for (i=0; i<N; i++) {
12197            PackageParser.Activity a = pkg.receivers.get(i);
12198            mReceivers.removeActivity(a, "receiver");
12199            if (DEBUG_REMOVE && chatty) {
12200                if (r == null) {
12201                    r = new StringBuilder(256);
12202                } else {
12203                    r.append(' ');
12204                }
12205                r.append(a.info.name);
12206            }
12207        }
12208        if (r != null) {
12209            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12210        }
12211
12212        N = pkg.activities.size();
12213        r = null;
12214        for (i=0; i<N; i++) {
12215            PackageParser.Activity a = pkg.activities.get(i);
12216            mActivities.removeActivity(a, "activity");
12217            if (DEBUG_REMOVE && chatty) {
12218                if (r == null) {
12219                    r = new StringBuilder(256);
12220                } else {
12221                    r.append(' ');
12222                }
12223                r.append(a.info.name);
12224            }
12225        }
12226        if (r != null) {
12227            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12228        }
12229
12230        mPermissionManager.removeAllPermissions(pkg, chatty);
12231
12232        N = pkg.instrumentation.size();
12233        r = null;
12234        for (i=0; i<N; i++) {
12235            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12236            mInstrumentation.remove(a.getComponentName());
12237            if (DEBUG_REMOVE && chatty) {
12238                if (r == null) {
12239                    r = new StringBuilder(256);
12240                } else {
12241                    r.append(' ');
12242                }
12243                r.append(a.info.name);
12244            }
12245        }
12246        if (r != null) {
12247            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12248        }
12249
12250        r = null;
12251        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12252            // Only system apps can hold shared libraries.
12253            if (pkg.libraryNames != null) {
12254                for (i = 0; i < pkg.libraryNames.size(); i++) {
12255                    String name = pkg.libraryNames.get(i);
12256                    if (removeSharedLibraryLPw(name, 0)) {
12257                        if (DEBUG_REMOVE && chatty) {
12258                            if (r == null) {
12259                                r = new StringBuilder(256);
12260                            } else {
12261                                r.append(' ');
12262                            }
12263                            r.append(name);
12264                        }
12265                    }
12266                }
12267            }
12268        }
12269
12270        r = null;
12271
12272        // Any package can hold static shared libraries.
12273        if (pkg.staticSharedLibName != null) {
12274            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12275                if (DEBUG_REMOVE && chatty) {
12276                    if (r == null) {
12277                        r = new StringBuilder(256);
12278                    } else {
12279                        r.append(' ');
12280                    }
12281                    r.append(pkg.staticSharedLibName);
12282                }
12283            }
12284        }
12285
12286        if (r != null) {
12287            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12288        }
12289    }
12290
12291
12292    final class ActivityIntentResolver
12293            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12294        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12295                boolean defaultOnly, int userId) {
12296            if (!sUserManager.exists(userId)) return null;
12297            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12298            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12299        }
12300
12301        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12302                int userId) {
12303            if (!sUserManager.exists(userId)) return null;
12304            mFlags = flags;
12305            return super.queryIntent(intent, resolvedType,
12306                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12307                    userId);
12308        }
12309
12310        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12311                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12312            if (!sUserManager.exists(userId)) return null;
12313            if (packageActivities == null) {
12314                return null;
12315            }
12316            mFlags = flags;
12317            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12318            final int N = packageActivities.size();
12319            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12320                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12321
12322            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12323            for (int i = 0; i < N; ++i) {
12324                intentFilters = packageActivities.get(i).intents;
12325                if (intentFilters != null && intentFilters.size() > 0) {
12326                    PackageParser.ActivityIntentInfo[] array =
12327                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12328                    intentFilters.toArray(array);
12329                    listCut.add(array);
12330                }
12331            }
12332            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12333        }
12334
12335        /**
12336         * Finds a privileged activity that matches the specified activity names.
12337         */
12338        private PackageParser.Activity findMatchingActivity(
12339                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12340            for (PackageParser.Activity sysActivity : activityList) {
12341                if (sysActivity.info.name.equals(activityInfo.name)) {
12342                    return sysActivity;
12343                }
12344                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12345                    return sysActivity;
12346                }
12347                if (sysActivity.info.targetActivity != null) {
12348                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12349                        return sysActivity;
12350                    }
12351                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12352                        return sysActivity;
12353                    }
12354                }
12355            }
12356            return null;
12357        }
12358
12359        public class IterGenerator<E> {
12360            public Iterator<E> generate(ActivityIntentInfo info) {
12361                return null;
12362            }
12363        }
12364
12365        public class ActionIterGenerator extends IterGenerator<String> {
12366            @Override
12367            public Iterator<String> generate(ActivityIntentInfo info) {
12368                return info.actionsIterator();
12369            }
12370        }
12371
12372        public class CategoriesIterGenerator extends IterGenerator<String> {
12373            @Override
12374            public Iterator<String> generate(ActivityIntentInfo info) {
12375                return info.categoriesIterator();
12376            }
12377        }
12378
12379        public class SchemesIterGenerator extends IterGenerator<String> {
12380            @Override
12381            public Iterator<String> generate(ActivityIntentInfo info) {
12382                return info.schemesIterator();
12383            }
12384        }
12385
12386        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12387            @Override
12388            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12389                return info.authoritiesIterator();
12390            }
12391        }
12392
12393        /**
12394         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12395         * MODIFIED. Do not pass in a list that should not be changed.
12396         */
12397        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12398                IterGenerator<T> generator, Iterator<T> searchIterator) {
12399            // loop through the set of actions; every one must be found in the intent filter
12400            while (searchIterator.hasNext()) {
12401                // we must have at least one filter in the list to consider a match
12402                if (intentList.size() == 0) {
12403                    break;
12404                }
12405
12406                final T searchAction = searchIterator.next();
12407
12408                // loop through the set of intent filters
12409                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12410                while (intentIter.hasNext()) {
12411                    final ActivityIntentInfo intentInfo = intentIter.next();
12412                    boolean selectionFound = false;
12413
12414                    // loop through the intent filter's selection criteria; at least one
12415                    // of them must match the searched criteria
12416                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12417                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12418                        final T intentSelection = intentSelectionIter.next();
12419                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12420                            selectionFound = true;
12421                            break;
12422                        }
12423                    }
12424
12425                    // the selection criteria wasn't found in this filter's set; this filter
12426                    // is not a potential match
12427                    if (!selectionFound) {
12428                        intentIter.remove();
12429                    }
12430                }
12431            }
12432        }
12433
12434        private boolean isProtectedAction(ActivityIntentInfo filter) {
12435            final Iterator<String> actionsIter = filter.actionsIterator();
12436            while (actionsIter != null && actionsIter.hasNext()) {
12437                final String filterAction = actionsIter.next();
12438                if (PROTECTED_ACTIONS.contains(filterAction)) {
12439                    return true;
12440                }
12441            }
12442            return false;
12443        }
12444
12445        /**
12446         * Adjusts the priority of the given intent filter according to policy.
12447         * <p>
12448         * <ul>
12449         * <li>The priority for non privileged applications is capped to '0'</li>
12450         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12451         * <li>The priority for unbundled updates to privileged applications is capped to the
12452         *      priority defined on the system partition</li>
12453         * </ul>
12454         * <p>
12455         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12456         * allowed to obtain any priority on any action.
12457         */
12458        private void adjustPriority(
12459                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12460            // nothing to do; priority is fine as-is
12461            if (intent.getPriority() <= 0) {
12462                return;
12463            }
12464
12465            final ActivityInfo activityInfo = intent.activity.info;
12466            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12467
12468            final boolean privilegedApp =
12469                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12470            if (!privilegedApp) {
12471                // non-privileged applications can never define a priority >0
12472                if (DEBUG_FILTERS) {
12473                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12474                            + " package: " + applicationInfo.packageName
12475                            + " activity: " + intent.activity.className
12476                            + " origPrio: " + intent.getPriority());
12477                }
12478                intent.setPriority(0);
12479                return;
12480            }
12481
12482            if (systemActivities == null) {
12483                // the system package is not disabled; we're parsing the system partition
12484                if (isProtectedAction(intent)) {
12485                    if (mDeferProtectedFilters) {
12486                        // We can't deal with these just yet. No component should ever obtain a
12487                        // >0 priority for a protected actions, with ONE exception -- the setup
12488                        // wizard. The setup wizard, however, cannot be known until we're able to
12489                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12490                        // until all intent filters have been processed. Chicken, meet egg.
12491                        // Let the filter temporarily have a high priority and rectify the
12492                        // priorities after all system packages have been scanned.
12493                        mProtectedFilters.add(intent);
12494                        if (DEBUG_FILTERS) {
12495                            Slog.i(TAG, "Protected action; save for later;"
12496                                    + " package: " + applicationInfo.packageName
12497                                    + " activity: " + intent.activity.className
12498                                    + " origPrio: " + intent.getPriority());
12499                        }
12500                        return;
12501                    } else {
12502                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12503                            Slog.i(TAG, "No setup wizard;"
12504                                + " All protected intents capped to priority 0");
12505                        }
12506                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12507                            if (DEBUG_FILTERS) {
12508                                Slog.i(TAG, "Found setup wizard;"
12509                                    + " allow priority " + intent.getPriority() + ";"
12510                                    + " package: " + intent.activity.info.packageName
12511                                    + " activity: " + intent.activity.className
12512                                    + " priority: " + intent.getPriority());
12513                            }
12514                            // setup wizard gets whatever it wants
12515                            return;
12516                        }
12517                        if (DEBUG_FILTERS) {
12518                            Slog.i(TAG, "Protected action; cap priority to 0;"
12519                                    + " package: " + intent.activity.info.packageName
12520                                    + " activity: " + intent.activity.className
12521                                    + " origPrio: " + intent.getPriority());
12522                        }
12523                        intent.setPriority(0);
12524                        return;
12525                    }
12526                }
12527                // privileged apps on the system image get whatever priority they request
12528                return;
12529            }
12530
12531            // privileged app unbundled update ... try to find the same activity
12532            final PackageParser.Activity foundActivity =
12533                    findMatchingActivity(systemActivities, activityInfo);
12534            if (foundActivity == null) {
12535                // this is a new activity; it cannot obtain >0 priority
12536                if (DEBUG_FILTERS) {
12537                    Slog.i(TAG, "New activity; cap priority to 0;"
12538                            + " package: " + applicationInfo.packageName
12539                            + " activity: " + intent.activity.className
12540                            + " origPrio: " + intent.getPriority());
12541                }
12542                intent.setPriority(0);
12543                return;
12544            }
12545
12546            // found activity, now check for filter equivalence
12547
12548            // a shallow copy is enough; we modify the list, not its contents
12549            final List<ActivityIntentInfo> intentListCopy =
12550                    new ArrayList<>(foundActivity.intents);
12551            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12552
12553            // find matching action subsets
12554            final Iterator<String> actionsIterator = intent.actionsIterator();
12555            if (actionsIterator != null) {
12556                getIntentListSubset(
12557                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12558                if (intentListCopy.size() == 0) {
12559                    // no more intents to match; we're not equivalent
12560                    if (DEBUG_FILTERS) {
12561                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12562                                + " package: " + applicationInfo.packageName
12563                                + " activity: " + intent.activity.className
12564                                + " origPrio: " + intent.getPriority());
12565                    }
12566                    intent.setPriority(0);
12567                    return;
12568                }
12569            }
12570
12571            // find matching category subsets
12572            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12573            if (categoriesIterator != null) {
12574                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12575                        categoriesIterator);
12576                if (intentListCopy.size() == 0) {
12577                    // no more intents to match; we're not equivalent
12578                    if (DEBUG_FILTERS) {
12579                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12580                                + " package: " + applicationInfo.packageName
12581                                + " activity: " + intent.activity.className
12582                                + " origPrio: " + intent.getPriority());
12583                    }
12584                    intent.setPriority(0);
12585                    return;
12586                }
12587            }
12588
12589            // find matching schemes subsets
12590            final Iterator<String> schemesIterator = intent.schemesIterator();
12591            if (schemesIterator != null) {
12592                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12593                        schemesIterator);
12594                if (intentListCopy.size() == 0) {
12595                    // no more intents to match; we're not equivalent
12596                    if (DEBUG_FILTERS) {
12597                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12598                                + " package: " + applicationInfo.packageName
12599                                + " activity: " + intent.activity.className
12600                                + " origPrio: " + intent.getPriority());
12601                    }
12602                    intent.setPriority(0);
12603                    return;
12604                }
12605            }
12606
12607            // find matching authorities subsets
12608            final Iterator<IntentFilter.AuthorityEntry>
12609                    authoritiesIterator = intent.authoritiesIterator();
12610            if (authoritiesIterator != null) {
12611                getIntentListSubset(intentListCopy,
12612                        new AuthoritiesIterGenerator(),
12613                        authoritiesIterator);
12614                if (intentListCopy.size() == 0) {
12615                    // no more intents to match; we're not equivalent
12616                    if (DEBUG_FILTERS) {
12617                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12618                                + " package: " + applicationInfo.packageName
12619                                + " activity: " + intent.activity.className
12620                                + " origPrio: " + intent.getPriority());
12621                    }
12622                    intent.setPriority(0);
12623                    return;
12624                }
12625            }
12626
12627            // we found matching filter(s); app gets the max priority of all intents
12628            int cappedPriority = 0;
12629            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12630                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12631            }
12632            if (intent.getPriority() > cappedPriority) {
12633                if (DEBUG_FILTERS) {
12634                    Slog.i(TAG, "Found matching filter(s);"
12635                            + " cap priority to " + cappedPriority + ";"
12636                            + " package: " + applicationInfo.packageName
12637                            + " activity: " + intent.activity.className
12638                            + " origPrio: " + intent.getPriority());
12639                }
12640                intent.setPriority(cappedPriority);
12641                return;
12642            }
12643            // all this for nothing; the requested priority was <= what was on the system
12644        }
12645
12646        public final void addActivity(PackageParser.Activity a, String type) {
12647            mActivities.put(a.getComponentName(), a);
12648            if (DEBUG_SHOW_INFO)
12649                Log.v(
12650                TAG, "  " + type + " " +
12651                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12652            if (DEBUG_SHOW_INFO)
12653                Log.v(TAG, "    Class=" + a.info.name);
12654            final int NI = a.intents.size();
12655            for (int j=0; j<NI; j++) {
12656                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12657                if ("activity".equals(type)) {
12658                    final PackageSetting ps =
12659                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12660                    final List<PackageParser.Activity> systemActivities =
12661                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12662                    adjustPriority(systemActivities, intent);
12663                }
12664                if (DEBUG_SHOW_INFO) {
12665                    Log.v(TAG, "    IntentFilter:");
12666                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12667                }
12668                if (!intent.debugCheck()) {
12669                    Log.w(TAG, "==> For Activity " + a.info.name);
12670                }
12671                addFilter(intent);
12672            }
12673        }
12674
12675        public final void removeActivity(PackageParser.Activity a, String type) {
12676            mActivities.remove(a.getComponentName());
12677            if (DEBUG_SHOW_INFO) {
12678                Log.v(TAG, "  " + type + " "
12679                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12680                                : a.info.name) + ":");
12681                Log.v(TAG, "    Class=" + a.info.name);
12682            }
12683            final int NI = a.intents.size();
12684            for (int j=0; j<NI; j++) {
12685                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12686                if (DEBUG_SHOW_INFO) {
12687                    Log.v(TAG, "    IntentFilter:");
12688                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12689                }
12690                removeFilter(intent);
12691            }
12692        }
12693
12694        @Override
12695        protected boolean allowFilterResult(
12696                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12697            ActivityInfo filterAi = filter.activity.info;
12698            for (int i=dest.size()-1; i>=0; i--) {
12699                ActivityInfo destAi = dest.get(i).activityInfo;
12700                if (destAi.name == filterAi.name
12701                        && destAi.packageName == filterAi.packageName) {
12702                    return false;
12703                }
12704            }
12705            return true;
12706        }
12707
12708        @Override
12709        protected ActivityIntentInfo[] newArray(int size) {
12710            return new ActivityIntentInfo[size];
12711        }
12712
12713        @Override
12714        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12715            if (!sUserManager.exists(userId)) return true;
12716            PackageParser.Package p = filter.activity.owner;
12717            if (p != null) {
12718                PackageSetting ps = (PackageSetting)p.mExtras;
12719                if (ps != null) {
12720                    // System apps are never considered stopped for purposes of
12721                    // filtering, because there may be no way for the user to
12722                    // actually re-launch them.
12723                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12724                            && ps.getStopped(userId);
12725                }
12726            }
12727            return false;
12728        }
12729
12730        @Override
12731        protected boolean isPackageForFilter(String packageName,
12732                PackageParser.ActivityIntentInfo info) {
12733            return packageName.equals(info.activity.owner.packageName);
12734        }
12735
12736        @Override
12737        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12738                int match, int userId) {
12739            if (!sUserManager.exists(userId)) return null;
12740            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12741                return null;
12742            }
12743            final PackageParser.Activity activity = info.activity;
12744            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12745            if (ps == null) {
12746                return null;
12747            }
12748            final PackageUserState userState = ps.readUserState(userId);
12749            ActivityInfo ai =
12750                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12751            if (ai == null) {
12752                return null;
12753            }
12754            final boolean matchExplicitlyVisibleOnly =
12755                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12756            final boolean matchVisibleToInstantApp =
12757                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12758            final boolean componentVisible =
12759                    matchVisibleToInstantApp
12760                    && info.isVisibleToInstantApp()
12761                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12762            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12763            // throw out filters that aren't visible to ephemeral apps
12764            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12765                return null;
12766            }
12767            // throw out instant app filters if we're not explicitly requesting them
12768            if (!matchInstantApp && userState.instantApp) {
12769                return null;
12770            }
12771            // throw out instant app filters if updates are available; will trigger
12772            // instant app resolution
12773            if (userState.instantApp && ps.isUpdateAvailable()) {
12774                return null;
12775            }
12776            final ResolveInfo res = new ResolveInfo();
12777            res.activityInfo = ai;
12778            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12779                res.filter = info;
12780            }
12781            if (info != null) {
12782                res.handleAllWebDataURI = info.handleAllWebDataURI();
12783            }
12784            res.priority = info.getPriority();
12785            res.preferredOrder = activity.owner.mPreferredOrder;
12786            //System.out.println("Result: " + res.activityInfo.className +
12787            //                   " = " + res.priority);
12788            res.match = match;
12789            res.isDefault = info.hasDefault;
12790            res.labelRes = info.labelRes;
12791            res.nonLocalizedLabel = info.nonLocalizedLabel;
12792            if (userNeedsBadging(userId)) {
12793                res.noResourceId = true;
12794            } else {
12795                res.icon = info.icon;
12796            }
12797            res.iconResourceId = info.icon;
12798            res.system = res.activityInfo.applicationInfo.isSystemApp();
12799            res.isInstantAppAvailable = userState.instantApp;
12800            return res;
12801        }
12802
12803        @Override
12804        protected void sortResults(List<ResolveInfo> results) {
12805            Collections.sort(results, mResolvePrioritySorter);
12806        }
12807
12808        @Override
12809        protected void dumpFilter(PrintWriter out, String prefix,
12810                PackageParser.ActivityIntentInfo filter) {
12811            out.print(prefix); out.print(
12812                    Integer.toHexString(System.identityHashCode(filter.activity)));
12813                    out.print(' ');
12814                    filter.activity.printComponentShortName(out);
12815                    out.print(" filter ");
12816                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12817        }
12818
12819        @Override
12820        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12821            return filter.activity;
12822        }
12823
12824        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12825            PackageParser.Activity activity = (PackageParser.Activity)label;
12826            out.print(prefix); out.print(
12827                    Integer.toHexString(System.identityHashCode(activity)));
12828                    out.print(' ');
12829                    activity.printComponentShortName(out);
12830            if (count > 1) {
12831                out.print(" ("); out.print(count); out.print(" filters)");
12832            }
12833            out.println();
12834        }
12835
12836        // Keys are String (activity class name), values are Activity.
12837        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12838                = new ArrayMap<ComponentName, PackageParser.Activity>();
12839        private int mFlags;
12840    }
12841
12842    private final class ServiceIntentResolver
12843            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12844        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12845                boolean defaultOnly, int userId) {
12846            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12847            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12848        }
12849
12850        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12851                int userId) {
12852            if (!sUserManager.exists(userId)) return null;
12853            mFlags = flags;
12854            return super.queryIntent(intent, resolvedType,
12855                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12856                    userId);
12857        }
12858
12859        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12860                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12861            if (!sUserManager.exists(userId)) return null;
12862            if (packageServices == null) {
12863                return null;
12864            }
12865            mFlags = flags;
12866            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12867            final int N = packageServices.size();
12868            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12869                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12870
12871            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12872            for (int i = 0; i < N; ++i) {
12873                intentFilters = packageServices.get(i).intents;
12874                if (intentFilters != null && intentFilters.size() > 0) {
12875                    PackageParser.ServiceIntentInfo[] array =
12876                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12877                    intentFilters.toArray(array);
12878                    listCut.add(array);
12879                }
12880            }
12881            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12882        }
12883
12884        public final void addService(PackageParser.Service s) {
12885            mServices.put(s.getComponentName(), s);
12886            if (DEBUG_SHOW_INFO) {
12887                Log.v(TAG, "  "
12888                        + (s.info.nonLocalizedLabel != null
12889                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12890                Log.v(TAG, "    Class=" + s.info.name);
12891            }
12892            final int NI = s.intents.size();
12893            int j;
12894            for (j=0; j<NI; j++) {
12895                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12896                if (DEBUG_SHOW_INFO) {
12897                    Log.v(TAG, "    IntentFilter:");
12898                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12899                }
12900                if (!intent.debugCheck()) {
12901                    Log.w(TAG, "==> For Service " + s.info.name);
12902                }
12903                addFilter(intent);
12904            }
12905        }
12906
12907        public final void removeService(PackageParser.Service s) {
12908            mServices.remove(s.getComponentName());
12909            if (DEBUG_SHOW_INFO) {
12910                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12911                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12912                Log.v(TAG, "    Class=" + s.info.name);
12913            }
12914            final int NI = s.intents.size();
12915            int j;
12916            for (j=0; j<NI; j++) {
12917                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12918                if (DEBUG_SHOW_INFO) {
12919                    Log.v(TAG, "    IntentFilter:");
12920                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12921                }
12922                removeFilter(intent);
12923            }
12924        }
12925
12926        @Override
12927        protected boolean allowFilterResult(
12928                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12929            ServiceInfo filterSi = filter.service.info;
12930            for (int i=dest.size()-1; i>=0; i--) {
12931                ServiceInfo destAi = dest.get(i).serviceInfo;
12932                if (destAi.name == filterSi.name
12933                        && destAi.packageName == filterSi.packageName) {
12934                    return false;
12935                }
12936            }
12937            return true;
12938        }
12939
12940        @Override
12941        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12942            return new PackageParser.ServiceIntentInfo[size];
12943        }
12944
12945        @Override
12946        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12947            if (!sUserManager.exists(userId)) return true;
12948            PackageParser.Package p = filter.service.owner;
12949            if (p != null) {
12950                PackageSetting ps = (PackageSetting)p.mExtras;
12951                if (ps != null) {
12952                    // System apps are never considered stopped for purposes of
12953                    // filtering, because there may be no way for the user to
12954                    // actually re-launch them.
12955                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12956                            && ps.getStopped(userId);
12957                }
12958            }
12959            return false;
12960        }
12961
12962        @Override
12963        protected boolean isPackageForFilter(String packageName,
12964                PackageParser.ServiceIntentInfo info) {
12965            return packageName.equals(info.service.owner.packageName);
12966        }
12967
12968        @Override
12969        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12970                int match, int userId) {
12971            if (!sUserManager.exists(userId)) return null;
12972            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12973            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12974                return null;
12975            }
12976            final PackageParser.Service service = info.service;
12977            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12978            if (ps == null) {
12979                return null;
12980            }
12981            final PackageUserState userState = ps.readUserState(userId);
12982            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12983                    userState, userId);
12984            if (si == null) {
12985                return null;
12986            }
12987            final boolean matchVisibleToInstantApp =
12988                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12989            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12990            // throw out filters that aren't visible to ephemeral apps
12991            if (matchVisibleToInstantApp
12992                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12993                return null;
12994            }
12995            // throw out ephemeral filters if we're not explicitly requesting them
12996            if (!isInstantApp && userState.instantApp) {
12997                return null;
12998            }
12999            // throw out instant app filters if updates are available; will trigger
13000            // instant app resolution
13001            if (userState.instantApp && ps.isUpdateAvailable()) {
13002                return null;
13003            }
13004            final ResolveInfo res = new ResolveInfo();
13005            res.serviceInfo = si;
13006            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13007                res.filter = filter;
13008            }
13009            res.priority = info.getPriority();
13010            res.preferredOrder = service.owner.mPreferredOrder;
13011            res.match = match;
13012            res.isDefault = info.hasDefault;
13013            res.labelRes = info.labelRes;
13014            res.nonLocalizedLabel = info.nonLocalizedLabel;
13015            res.icon = info.icon;
13016            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13017            return res;
13018        }
13019
13020        @Override
13021        protected void sortResults(List<ResolveInfo> results) {
13022            Collections.sort(results, mResolvePrioritySorter);
13023        }
13024
13025        @Override
13026        protected void dumpFilter(PrintWriter out, String prefix,
13027                PackageParser.ServiceIntentInfo filter) {
13028            out.print(prefix); out.print(
13029                    Integer.toHexString(System.identityHashCode(filter.service)));
13030                    out.print(' ');
13031                    filter.service.printComponentShortName(out);
13032                    out.print(" filter ");
13033                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13034                    if (filter.service.info.permission != null) {
13035                        out.print(" permission "); out.println(filter.service.info.permission);
13036                    } else {
13037                        out.println();
13038                    }
13039        }
13040
13041        @Override
13042        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13043            return filter.service;
13044        }
13045
13046        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13047            PackageParser.Service service = (PackageParser.Service)label;
13048            out.print(prefix); out.print(
13049                    Integer.toHexString(System.identityHashCode(service)));
13050                    out.print(' ');
13051                    service.printComponentShortName(out);
13052            if (count > 1) {
13053                out.print(" ("); out.print(count); out.print(" filters)");
13054            }
13055            out.println();
13056        }
13057
13058//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13059//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13060//            final List<ResolveInfo> retList = Lists.newArrayList();
13061//            while (i.hasNext()) {
13062//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13063//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13064//                    retList.add(resolveInfo);
13065//                }
13066//            }
13067//            return retList;
13068//        }
13069
13070        // Keys are String (activity class name), values are Activity.
13071        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13072                = new ArrayMap<ComponentName, PackageParser.Service>();
13073        private int mFlags;
13074    }
13075
13076    private final class ProviderIntentResolver
13077            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13078        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13079                boolean defaultOnly, int userId) {
13080            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13081            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13082        }
13083
13084        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13085                int userId) {
13086            if (!sUserManager.exists(userId))
13087                return null;
13088            mFlags = flags;
13089            return super.queryIntent(intent, resolvedType,
13090                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13091                    userId);
13092        }
13093
13094        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13095                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13096            if (!sUserManager.exists(userId))
13097                return null;
13098            if (packageProviders == null) {
13099                return null;
13100            }
13101            mFlags = flags;
13102            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13103            final int N = packageProviders.size();
13104            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13105                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13106
13107            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13108            for (int i = 0; i < N; ++i) {
13109                intentFilters = packageProviders.get(i).intents;
13110                if (intentFilters != null && intentFilters.size() > 0) {
13111                    PackageParser.ProviderIntentInfo[] array =
13112                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13113                    intentFilters.toArray(array);
13114                    listCut.add(array);
13115                }
13116            }
13117            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13118        }
13119
13120        public final void addProvider(PackageParser.Provider p) {
13121            if (mProviders.containsKey(p.getComponentName())) {
13122                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13123                return;
13124            }
13125
13126            mProviders.put(p.getComponentName(), p);
13127            if (DEBUG_SHOW_INFO) {
13128                Log.v(TAG, "  "
13129                        + (p.info.nonLocalizedLabel != null
13130                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13131                Log.v(TAG, "    Class=" + p.info.name);
13132            }
13133            final int NI = p.intents.size();
13134            int j;
13135            for (j = 0; j < NI; j++) {
13136                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13137                if (DEBUG_SHOW_INFO) {
13138                    Log.v(TAG, "    IntentFilter:");
13139                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13140                }
13141                if (!intent.debugCheck()) {
13142                    Log.w(TAG, "==> For Provider " + p.info.name);
13143                }
13144                addFilter(intent);
13145            }
13146        }
13147
13148        public final void removeProvider(PackageParser.Provider p) {
13149            mProviders.remove(p.getComponentName());
13150            if (DEBUG_SHOW_INFO) {
13151                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13152                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13153                Log.v(TAG, "    Class=" + p.info.name);
13154            }
13155            final int NI = p.intents.size();
13156            int j;
13157            for (j = 0; j < NI; j++) {
13158                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13159                if (DEBUG_SHOW_INFO) {
13160                    Log.v(TAG, "    IntentFilter:");
13161                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13162                }
13163                removeFilter(intent);
13164            }
13165        }
13166
13167        @Override
13168        protected boolean allowFilterResult(
13169                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13170            ProviderInfo filterPi = filter.provider.info;
13171            for (int i = dest.size() - 1; i >= 0; i--) {
13172                ProviderInfo destPi = dest.get(i).providerInfo;
13173                if (destPi.name == filterPi.name
13174                        && destPi.packageName == filterPi.packageName) {
13175                    return false;
13176                }
13177            }
13178            return true;
13179        }
13180
13181        @Override
13182        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13183            return new PackageParser.ProviderIntentInfo[size];
13184        }
13185
13186        @Override
13187        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13188            if (!sUserManager.exists(userId))
13189                return true;
13190            PackageParser.Package p = filter.provider.owner;
13191            if (p != null) {
13192                PackageSetting ps = (PackageSetting) p.mExtras;
13193                if (ps != null) {
13194                    // System apps are never considered stopped for purposes of
13195                    // filtering, because there may be no way for the user to
13196                    // actually re-launch them.
13197                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13198                            && ps.getStopped(userId);
13199                }
13200            }
13201            return false;
13202        }
13203
13204        @Override
13205        protected boolean isPackageForFilter(String packageName,
13206                PackageParser.ProviderIntentInfo info) {
13207            return packageName.equals(info.provider.owner.packageName);
13208        }
13209
13210        @Override
13211        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13212                int match, int userId) {
13213            if (!sUserManager.exists(userId))
13214                return null;
13215            final PackageParser.ProviderIntentInfo info = filter;
13216            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13217                return null;
13218            }
13219            final PackageParser.Provider provider = info.provider;
13220            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13221            if (ps == null) {
13222                return null;
13223            }
13224            final PackageUserState userState = ps.readUserState(userId);
13225            final boolean matchVisibleToInstantApp =
13226                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13227            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13228            // throw out filters that aren't visible to instant applications
13229            if (matchVisibleToInstantApp
13230                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13231                return null;
13232            }
13233            // throw out instant application filters if we're not explicitly requesting them
13234            if (!isInstantApp && userState.instantApp) {
13235                return null;
13236            }
13237            // throw out instant application filters if updates are available; will trigger
13238            // instant application resolution
13239            if (userState.instantApp && ps.isUpdateAvailable()) {
13240                return null;
13241            }
13242            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13243                    userState, userId);
13244            if (pi == null) {
13245                return null;
13246            }
13247            final ResolveInfo res = new ResolveInfo();
13248            res.providerInfo = pi;
13249            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13250                res.filter = filter;
13251            }
13252            res.priority = info.getPriority();
13253            res.preferredOrder = provider.owner.mPreferredOrder;
13254            res.match = match;
13255            res.isDefault = info.hasDefault;
13256            res.labelRes = info.labelRes;
13257            res.nonLocalizedLabel = info.nonLocalizedLabel;
13258            res.icon = info.icon;
13259            res.system = res.providerInfo.applicationInfo.isSystemApp();
13260            return res;
13261        }
13262
13263        @Override
13264        protected void sortResults(List<ResolveInfo> results) {
13265            Collections.sort(results, mResolvePrioritySorter);
13266        }
13267
13268        @Override
13269        protected void dumpFilter(PrintWriter out, String prefix,
13270                PackageParser.ProviderIntentInfo filter) {
13271            out.print(prefix);
13272            out.print(
13273                    Integer.toHexString(System.identityHashCode(filter.provider)));
13274            out.print(' ');
13275            filter.provider.printComponentShortName(out);
13276            out.print(" filter ");
13277            out.println(Integer.toHexString(System.identityHashCode(filter)));
13278        }
13279
13280        @Override
13281        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13282            return filter.provider;
13283        }
13284
13285        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13286            PackageParser.Provider provider = (PackageParser.Provider)label;
13287            out.print(prefix); out.print(
13288                    Integer.toHexString(System.identityHashCode(provider)));
13289                    out.print(' ');
13290                    provider.printComponentShortName(out);
13291            if (count > 1) {
13292                out.print(" ("); out.print(count); out.print(" filters)");
13293            }
13294            out.println();
13295        }
13296
13297        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13298                = new ArrayMap<ComponentName, PackageParser.Provider>();
13299        private int mFlags;
13300    }
13301
13302    static final class InstantAppIntentResolver
13303            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13304            AuxiliaryResolveInfo.AuxiliaryFilter> {
13305        /**
13306         * The result that has the highest defined order. Ordering applies on a
13307         * per-package basis. Mapping is from package name to Pair of order and
13308         * EphemeralResolveInfo.
13309         * <p>
13310         * NOTE: This is implemented as a field variable for convenience and efficiency.
13311         * By having a field variable, we're able to track filter ordering as soon as
13312         * a non-zero order is defined. Otherwise, multiple loops across the result set
13313         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13314         * this needs to be contained entirely within {@link #filterResults}.
13315         */
13316        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13317
13318        @Override
13319        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13320            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13321        }
13322
13323        @Override
13324        protected boolean isPackageForFilter(String packageName,
13325                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13326            return true;
13327        }
13328
13329        @Override
13330        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13331                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13332            if (!sUserManager.exists(userId)) {
13333                return null;
13334            }
13335            final String packageName = responseObj.resolveInfo.getPackageName();
13336            final Integer order = responseObj.getOrder();
13337            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13338                    mOrderResult.get(packageName);
13339            // ordering is enabled and this item's order isn't high enough
13340            if (lastOrderResult != null && lastOrderResult.first >= order) {
13341                return null;
13342            }
13343            final InstantAppResolveInfo res = responseObj.resolveInfo;
13344            if (order > 0) {
13345                // non-zero order, enable ordering
13346                mOrderResult.put(packageName, new Pair<>(order, res));
13347            }
13348            return responseObj;
13349        }
13350
13351        @Override
13352        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13353            // only do work if ordering is enabled [most of the time it won't be]
13354            if (mOrderResult.size() == 0) {
13355                return;
13356            }
13357            int resultSize = results.size();
13358            for (int i = 0; i < resultSize; i++) {
13359                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13360                final String packageName = info.getPackageName();
13361                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13362                if (savedInfo == null) {
13363                    // package doesn't having ordering
13364                    continue;
13365                }
13366                if (savedInfo.second == info) {
13367                    // circled back to the highest ordered item; remove from order list
13368                    mOrderResult.remove(packageName);
13369                    if (mOrderResult.size() == 0) {
13370                        // no more ordered items
13371                        break;
13372                    }
13373                    continue;
13374                }
13375                // item has a worse order, remove it from the result list
13376                results.remove(i);
13377                resultSize--;
13378                i--;
13379            }
13380        }
13381    }
13382
13383    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13384            new Comparator<ResolveInfo>() {
13385        public int compare(ResolveInfo r1, ResolveInfo r2) {
13386            int v1 = r1.priority;
13387            int v2 = r2.priority;
13388            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13389            if (v1 != v2) {
13390                return (v1 > v2) ? -1 : 1;
13391            }
13392            v1 = r1.preferredOrder;
13393            v2 = r2.preferredOrder;
13394            if (v1 != v2) {
13395                return (v1 > v2) ? -1 : 1;
13396            }
13397            if (r1.isDefault != r2.isDefault) {
13398                return r1.isDefault ? -1 : 1;
13399            }
13400            v1 = r1.match;
13401            v2 = r2.match;
13402            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13403            if (v1 != v2) {
13404                return (v1 > v2) ? -1 : 1;
13405            }
13406            if (r1.system != r2.system) {
13407                return r1.system ? -1 : 1;
13408            }
13409            if (r1.activityInfo != null) {
13410                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13411            }
13412            if (r1.serviceInfo != null) {
13413                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13414            }
13415            if (r1.providerInfo != null) {
13416                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13417            }
13418            return 0;
13419        }
13420    };
13421
13422    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13423            new Comparator<ProviderInfo>() {
13424        public int compare(ProviderInfo p1, ProviderInfo p2) {
13425            final int v1 = p1.initOrder;
13426            final int v2 = p2.initOrder;
13427            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13428        }
13429    };
13430
13431    @Override
13432    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13433            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13434            final int[] userIds, int[] instantUserIds) {
13435        mHandler.post(new Runnable() {
13436            @Override
13437            public void run() {
13438                try {
13439                    final IActivityManager am = ActivityManager.getService();
13440                    if (am == null) return;
13441                    final int[] resolvedUserIds;
13442                    if (userIds == null) {
13443                        resolvedUserIds = am.getRunningUserIds();
13444                    } else {
13445                        resolvedUserIds = userIds;
13446                    }
13447                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13448                            resolvedUserIds, false);
13449                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13450                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13451                                instantUserIds, true);
13452                    }
13453                } catch (RemoteException ex) {
13454                }
13455            }
13456        });
13457    }
13458
13459    @Override
13460    public void notifyPackageAdded(String packageName) {
13461        final PackageListObserver[] observers;
13462        synchronized (mPackages) {
13463            if (mPackageListObservers.size() == 0) {
13464                return;
13465            }
13466            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13467        }
13468        for (int i = observers.length - 1; i >= 0; --i) {
13469            observers[i].onPackageAdded(packageName);
13470        }
13471    }
13472
13473    @Override
13474    public void notifyPackageRemoved(String packageName) {
13475        final PackageListObserver[] observers;
13476        synchronized (mPackages) {
13477            if (mPackageListObservers.size() == 0) {
13478                return;
13479            }
13480            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13481        }
13482        for (int i = observers.length - 1; i >= 0; --i) {
13483            observers[i].onPackageRemoved(packageName);
13484        }
13485    }
13486
13487    /**
13488     * Sends a broadcast for the given action.
13489     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13490     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13491     * the system and applications allowed to see instant applications to receive package
13492     * lifecycle events for instant applications.
13493     */
13494    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13495            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13496            int[] userIds, boolean isInstantApp)
13497                    throws RemoteException {
13498        for (int id : userIds) {
13499            final Intent intent = new Intent(action,
13500                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13501            final String[] requiredPermissions =
13502                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13503            if (extras != null) {
13504                intent.putExtras(extras);
13505            }
13506            if (targetPkg != null) {
13507                intent.setPackage(targetPkg);
13508            }
13509            // Modify the UID when posting to other users
13510            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13511            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13512                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13513                intent.putExtra(Intent.EXTRA_UID, uid);
13514            }
13515            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13516            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13517            if (DEBUG_BROADCASTS) {
13518                RuntimeException here = new RuntimeException("here");
13519                here.fillInStackTrace();
13520                Slog.d(TAG, "Sending to user " + id + ": "
13521                        + intent.toShortString(false, true, false, false)
13522                        + " " + intent.getExtras(), here);
13523            }
13524            am.broadcastIntent(null, intent, null, finishedReceiver,
13525                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13526                    null, finishedReceiver != null, false, id);
13527        }
13528    }
13529
13530    /**
13531     * Check if the external storage media is available. This is true if there
13532     * is a mounted external storage medium or if the external storage is
13533     * emulated.
13534     */
13535    private boolean isExternalMediaAvailable() {
13536        return mMediaMounted || Environment.isExternalStorageEmulated();
13537    }
13538
13539    @Override
13540    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13541        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13542            return null;
13543        }
13544        if (!isExternalMediaAvailable()) {
13545                // If the external storage is no longer mounted at this point,
13546                // the caller may not have been able to delete all of this
13547                // packages files and can not delete any more.  Bail.
13548            return null;
13549        }
13550        synchronized (mPackages) {
13551            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13552            if (lastPackage != null) {
13553                pkgs.remove(lastPackage);
13554            }
13555            if (pkgs.size() > 0) {
13556                return pkgs.get(0);
13557            }
13558        }
13559        return null;
13560    }
13561
13562    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13563        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13564                userId, andCode ? 1 : 0, packageName);
13565        if (mSystemReady) {
13566            msg.sendToTarget();
13567        } else {
13568            if (mPostSystemReadyMessages == null) {
13569                mPostSystemReadyMessages = new ArrayList<>();
13570            }
13571            mPostSystemReadyMessages.add(msg);
13572        }
13573    }
13574
13575    void startCleaningPackages() {
13576        // reader
13577        if (!isExternalMediaAvailable()) {
13578            return;
13579        }
13580        synchronized (mPackages) {
13581            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13582                return;
13583            }
13584        }
13585        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13586        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13587        IActivityManager am = ActivityManager.getService();
13588        if (am != null) {
13589            int dcsUid = -1;
13590            synchronized (mPackages) {
13591                if (!mDefaultContainerWhitelisted) {
13592                    mDefaultContainerWhitelisted = true;
13593                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13594                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13595                }
13596            }
13597            try {
13598                if (dcsUid > 0) {
13599                    am.backgroundWhitelistUid(dcsUid);
13600                }
13601                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13602                        UserHandle.USER_SYSTEM);
13603            } catch (RemoteException e) {
13604            }
13605        }
13606    }
13607
13608    /**
13609     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13610     * it is acting on behalf on an enterprise or the user).
13611     *
13612     * Note that the ordering of the conditionals in this method is important. The checks we perform
13613     * are as follows, in this order:
13614     *
13615     * 1) If the install is being performed by a system app, we can trust the app to have set the
13616     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13617     *    what it is.
13618     * 2) If the install is being performed by a device or profile owner app, the install reason
13619     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13620     *    set the install reason correctly. If the app targets an older SDK version where install
13621     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13622     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13623     * 3) In all other cases, the install is being performed by a regular app that is neither part
13624     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13625     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13626     *    set to enterprise policy and if so, change it to unknown instead.
13627     */
13628    private int fixUpInstallReason(String installerPackageName, int installerUid,
13629            int installReason) {
13630        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13631                == PERMISSION_GRANTED) {
13632            // If the install is being performed by a system app, we trust that app to have set the
13633            // install reason correctly.
13634            return installReason;
13635        }
13636        final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13637                UserHandle.getUserId(installerUid));
13638        if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13639            // If the install is being performed by a device or profile owner, the install
13640            // reason should be enterprise policy.
13641            return PackageManager.INSTALL_REASON_POLICY;
13642        }
13643
13644
13645        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13646            // If the install is being performed by a regular app (i.e. neither system app nor
13647            // device or profile owner), we have no reason to believe that the app is acting on
13648            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13649            // change it to unknown instead.
13650            return PackageManager.INSTALL_REASON_UNKNOWN;
13651        }
13652
13653        // If the install is being performed by a regular app and the install reason was set to any
13654        // value but enterprise policy, leave the install reason unchanged.
13655        return installReason;
13656    }
13657
13658    /**
13659     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13660     * install commit.
13661     */
13662    void earlyBindToDefContainer() {
13663        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13664    }
13665
13666    void installStage(String packageName, File stagedDir,
13667            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13668            String installerPackageName, int installerUid, UserHandle user,
13669            PackageParser.SigningDetails signingDetails) {
13670        if (DEBUG_INSTANT) {
13671            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13672                Slog.d(TAG, "Ephemeral install of " + packageName);
13673            }
13674        }
13675        final VerificationInfo verificationInfo = new VerificationInfo(
13676                sessionParams.originatingUri, sessionParams.referrerUri,
13677                sessionParams.originatingUid, installerUid);
13678
13679        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13680
13681        final Message msg = mHandler.obtainMessage(INIT_COPY);
13682        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13683                sessionParams.installReason);
13684        final InstallParams params = new InstallParams(origin, null, observer,
13685                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13686                verificationInfo, user, sessionParams.abiOverride,
13687                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13688        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13689        msg.obj = params;
13690
13691        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13692                System.identityHashCode(msg.obj));
13693        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13694                System.identityHashCode(msg.obj));
13695
13696        mHandler.sendMessage(msg);
13697    }
13698
13699    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13700            int userId) {
13701        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13702        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13703        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13704        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13705        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13706                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13707
13708        // Send a session commit broadcast
13709        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13710        info.installReason = pkgSetting.getInstallReason(userId);
13711        info.appPackageName = packageName;
13712        sendSessionCommitBroadcast(info, userId);
13713    }
13714
13715    @Override
13716    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13717            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13718        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13719            return;
13720        }
13721        Bundle extras = new Bundle(1);
13722        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13723        final int uid = UserHandle.getUid(
13724                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13725        extras.putInt(Intent.EXTRA_UID, uid);
13726
13727        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13728                packageName, extras, 0, null, null, userIds, instantUserIds);
13729        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13730            mHandler.post(() -> {
13731                        for (int userId : userIds) {
13732                            sendBootCompletedBroadcastToSystemApp(
13733                                    packageName, includeStopped, userId);
13734                        }
13735                    }
13736            );
13737        }
13738    }
13739
13740    /**
13741     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13742     * automatically without needing an explicit launch.
13743     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13744     */
13745    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13746            int userId) {
13747        // If user is not running, the app didn't miss any broadcast
13748        if (!mUserManagerInternal.isUserRunning(userId)) {
13749            return;
13750        }
13751        final IActivityManager am = ActivityManager.getService();
13752        try {
13753            // Deliver LOCKED_BOOT_COMPLETED first
13754            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13755                    .setPackage(packageName);
13756            if (includeStopped) {
13757                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13758            }
13759            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13760            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13761                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13762
13763            // Deliver BOOT_COMPLETED only if user is unlocked
13764            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13765                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13766                if (includeStopped) {
13767                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13768                }
13769                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13770                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13771            }
13772        } catch (RemoteException e) {
13773            throw e.rethrowFromSystemServer();
13774        }
13775    }
13776
13777    @Override
13778    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13779            int userId) {
13780        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13781        PackageSetting pkgSetting;
13782        final int callingUid = Binder.getCallingUid();
13783        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13784                true /* requireFullPermission */, true /* checkShell */,
13785                "setApplicationHiddenSetting for user " + userId);
13786
13787        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13788            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13789            return false;
13790        }
13791
13792        long callingId = Binder.clearCallingIdentity();
13793        try {
13794            boolean sendAdded = false;
13795            boolean sendRemoved = false;
13796            // writer
13797            synchronized (mPackages) {
13798                pkgSetting = mSettings.mPackages.get(packageName);
13799                if (pkgSetting == null) {
13800                    return false;
13801                }
13802                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13803                    return false;
13804                }
13805                // Do not allow "android" is being disabled
13806                if ("android".equals(packageName)) {
13807                    Slog.w(TAG, "Cannot hide package: android");
13808                    return false;
13809                }
13810                // Cannot hide static shared libs as they are considered
13811                // a part of the using app (emulating static linking). Also
13812                // static libs are installed always on internal storage.
13813                PackageParser.Package pkg = mPackages.get(packageName);
13814                if (pkg != null && pkg.staticSharedLibName != null) {
13815                    Slog.w(TAG, "Cannot hide package: " + packageName
13816                            + " providing static shared library: "
13817                            + pkg.staticSharedLibName);
13818                    return false;
13819                }
13820                // Only allow protected packages to hide themselves.
13821                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13822                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13823                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13824                    return false;
13825                }
13826
13827                if (pkgSetting.getHidden(userId) != hidden) {
13828                    pkgSetting.setHidden(hidden, userId);
13829                    mSettings.writePackageRestrictionsLPr(userId);
13830                    if (hidden) {
13831                        sendRemoved = true;
13832                    } else {
13833                        sendAdded = true;
13834                    }
13835                }
13836            }
13837            if (sendAdded) {
13838                sendPackageAddedForUser(packageName, pkgSetting, userId);
13839                return true;
13840            }
13841            if (sendRemoved) {
13842                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13843                        "hiding pkg");
13844                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13845                return true;
13846            }
13847        } finally {
13848            Binder.restoreCallingIdentity(callingId);
13849        }
13850        return false;
13851    }
13852
13853    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13854            int userId) {
13855        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13856        info.removedPackage = packageName;
13857        info.installerPackageName = pkgSetting.installerPackageName;
13858        info.removedUsers = new int[] {userId};
13859        info.broadcastUsers = new int[] {userId};
13860        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13861        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13862    }
13863
13864    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13865            PersistableBundle launcherExtras) {
13866        if (pkgList.length > 0) {
13867            Bundle extras = new Bundle(1);
13868            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13869            if (launcherExtras != null) {
13870                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13871                        new Bundle(launcherExtras.deepCopy()));
13872            }
13873            sendPackageBroadcast(
13874                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13875                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13876                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13877                    new int[] {userId}, null);
13878        }
13879    }
13880
13881    /**
13882     * Returns true if application is not found or there was an error. Otherwise it returns
13883     * the hidden state of the package for the given user.
13884     */
13885    @Override
13886    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13888        final int callingUid = Binder.getCallingUid();
13889        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13890                true /* requireFullPermission */, false /* checkShell */,
13891                "getApplicationHidden for user " + userId);
13892        PackageSetting ps;
13893        long callingId = Binder.clearCallingIdentity();
13894        try {
13895            // writer
13896            synchronized (mPackages) {
13897                ps = mSettings.mPackages.get(packageName);
13898                if (ps == null) {
13899                    return true;
13900                }
13901                if (filterAppAccessLPr(ps, callingUid, userId)) {
13902                    return true;
13903                }
13904                return ps.getHidden(userId);
13905            }
13906        } finally {
13907            Binder.restoreCallingIdentity(callingId);
13908        }
13909    }
13910
13911    /**
13912     * @hide
13913     */
13914    @Override
13915    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13916            int installReason) {
13917        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13918                null);
13919        PackageSetting pkgSetting;
13920        final int callingUid = Binder.getCallingUid();
13921        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13922                true /* requireFullPermission */, true /* checkShell */,
13923                "installExistingPackage for user " + userId);
13924        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13925            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13926        }
13927
13928        long callingId = Binder.clearCallingIdentity();
13929        try {
13930            boolean installed = false;
13931            final boolean instantApp =
13932                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13933            final boolean fullApp =
13934                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13935
13936            // writer
13937            synchronized (mPackages) {
13938                pkgSetting = mSettings.mPackages.get(packageName);
13939                if (pkgSetting == null) {
13940                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13941                }
13942                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13943                    // only allow the existing package to be used if it's installed as a full
13944                    // application for at least one user
13945                    boolean installAllowed = false;
13946                    for (int checkUserId : sUserManager.getUserIds()) {
13947                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13948                        if (installAllowed) {
13949                            break;
13950                        }
13951                    }
13952                    if (!installAllowed) {
13953                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13954                    }
13955                }
13956                if (!pkgSetting.getInstalled(userId)) {
13957                    pkgSetting.setInstalled(true, userId);
13958                    pkgSetting.setHidden(false, userId);
13959                    pkgSetting.setInstallReason(installReason, userId);
13960                    mSettings.writePackageRestrictionsLPr(userId);
13961                    mSettings.writeKernelMappingLPr(pkgSetting);
13962                    installed = true;
13963                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13964                    // upgrade app from instant to full; we don't allow app downgrade
13965                    installed = true;
13966                }
13967                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13968            }
13969
13970            if (installed) {
13971                if (pkgSetting.pkg != null) {
13972                    synchronized (mInstallLock) {
13973                        // We don't need to freeze for a brand new install
13974                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13975                    }
13976                }
13977                sendPackageAddedForUser(packageName, pkgSetting, userId);
13978                synchronized (mPackages) {
13979                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13980                }
13981            }
13982        } finally {
13983            Binder.restoreCallingIdentity(callingId);
13984        }
13985
13986        return PackageManager.INSTALL_SUCCEEDED;
13987    }
13988
13989    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13990            boolean instantApp, boolean fullApp) {
13991        // no state specified; do nothing
13992        if (!instantApp && !fullApp) {
13993            return;
13994        }
13995        if (userId != UserHandle.USER_ALL) {
13996            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13997                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13998            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13999                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14000            }
14001        } else {
14002            for (int currentUserId : sUserManager.getUserIds()) {
14003                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14004                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14005                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14006                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14007                }
14008            }
14009        }
14010    }
14011
14012    boolean isUserRestricted(int userId, String restrictionKey) {
14013        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14014        if (restrictions.getBoolean(restrictionKey, false)) {
14015            Log.w(TAG, "User is restricted: " + restrictionKey);
14016            return true;
14017        }
14018        return false;
14019    }
14020
14021    @Override
14022    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14023            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14024            String callingPackage, int userId) {
14025        try {
14026            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14027        } catch (SecurityException e) {
14028            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14029                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14030                            + Manifest.permission.MANAGE_USERS);
14031        }
14032        final int callingUid = Binder.getCallingUid();
14033        if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID
14034                && getPackageUid(callingPackage, 0, userId) != callingUid) {
14035            throw new SecurityException("Calling package " + callingPackage + " in user "
14036                    + userId + " does not belong to calling uid " + callingUid);
14037        }
14038        if (!PLATFORM_PACKAGE_NAME.equals(callingPackage)
14039                && mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId) != null) {
14040            throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
14041                    + userId + " has an active DO or PO");
14042        }
14043        if (ArrayUtils.isEmpty(packageNames)) {
14044            return packageNames;
14045        }
14046
14047        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14048        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14049        final long callingId = Binder.clearCallingIdentity();
14050        try {
14051            synchronized (mPackages) {
14052                for (int i = 0; i < packageNames.length; i++) {
14053                    final String packageName = packageNames[i];
14054                    if (callingPackage.equals(packageName)) {
14055                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14056                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14057                        unactionedPackages.add(packageName);
14058                        continue;
14059                    }
14060                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14061                    if (pkgSetting == null
14062                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14063                        Slog.w(TAG, "Could not find package setting for package: " + packageName
14064                                + ". Skipping suspending/un-suspending.");
14065                        unactionedPackages.add(packageName);
14066                        continue;
14067                    }
14068                    if (!canSuspendPackageForUserLocked(packageName, userId)) {
14069                        unactionedPackages.add(packageName);
14070                        continue;
14071                    }
14072                    pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14073                            launcherExtras, userId);
14074                    changedPackagesList.add(packageName);
14075                }
14076            }
14077        } finally {
14078            Binder.restoreCallingIdentity(callingId);
14079        }
14080        if (!changedPackagesList.isEmpty()) {
14081            final String[] changedPackages = changedPackagesList.toArray(
14082                    new String[changedPackagesList.size()]);
14083            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14084            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14085            synchronized (mPackages) {
14086                scheduleWritePackageRestrictionsLocked(userId);
14087            }
14088        }
14089        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14090    }
14091
14092    @Override
14093    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14094        final int callingUid = Binder.getCallingUid();
14095        if (getPackageUid(packageName, 0, userId) != callingUid) {
14096            throw new SecurityException("Calling package " + packageName
14097                    + " does not belong to calling uid " + callingUid);
14098        }
14099        synchronized (mPackages) {
14100            final PackageSetting ps = mSettings.mPackages.get(packageName);
14101            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14102                throw new IllegalArgumentException("Unknown target package: " + packageName);
14103            }
14104            final PackageUserState packageUserState = ps.readUserState(userId);
14105            if (packageUserState.suspended) {
14106                return packageUserState.suspendedAppExtras;
14107            }
14108            return null;
14109        }
14110    }
14111
14112    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14113            PersistableBundle appExtras, int userId) {
14114        final String action;
14115        final Bundle intentExtras = new Bundle();
14116        if (suspended) {
14117            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14118            if (appExtras != null) {
14119                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14120                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14121            }
14122        } else {
14123            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14124        }
14125        mHandler.post(new Runnable() {
14126            @Override
14127            public void run() {
14128                try {
14129                    final IActivityManager am = ActivityManager.getService();
14130                    if (am == null) {
14131                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14132                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14133                        return;
14134                    }
14135                    final int[] targetUserIds = new int[] {userId};
14136                    for (String packageName : affectedPackages) {
14137                        doSendBroadcast(am, action, null, intentExtras,
14138                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14139                                targetUserIds, false);
14140                    }
14141                } catch (RemoteException ex) {
14142                    // Shouldn't happen as AMS is in the same process.
14143                }
14144            }
14145        });
14146    }
14147
14148    @Override
14149    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14150        final int callingUid = Binder.getCallingUid();
14151        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14152                true /* requireFullPermission */, false /* checkShell */,
14153                "isPackageSuspendedForUser for user " + userId);
14154        synchronized (mPackages) {
14155            final PackageSetting ps = mSettings.mPackages.get(packageName);
14156            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14157                throw new IllegalArgumentException("Unknown target package: " + packageName);
14158            }
14159            return ps.getSuspended(userId);
14160        }
14161    }
14162
14163    /**
14164     * Immediately unsuspends any packages suspended by the given package. To be called
14165     * when such a package's data is cleared or it is removed from the device.
14166     *
14167     * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
14168     * synchronously
14169     *
14170     * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission
14171     * @param affectedUser The user for which the changes are taking place.
14172     */
14173    void unsuspendForSuspendingPackage(String packageName, int affectedUser) {
14174        final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14175                : new int[] {affectedUser};
14176        for (int userId : userIds) {
14177            List<String> affectedPackages = new ArrayList<>();
14178            synchronized (mPackages) {
14179                for (PackageSetting ps : mSettings.mPackages.values()) {
14180                    final PackageUserState pus = ps.readUserState(userId);
14181                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14182                        ps.setSuspended(false, null, null, null, null, userId);
14183                        affectedPackages.add(ps.name);
14184                    }
14185                }
14186            }
14187            if (!affectedPackages.isEmpty()) {
14188                final String[] packageArray = affectedPackages.toArray(
14189                        new String[affectedPackages.size()]);
14190                sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
14191                sendPackagesSuspendedForUser(packageArray, userId, false, null);
14192                // Write package restrictions immediately to avoid an inconsistent state.
14193                mSettings.writePackageRestrictionsLPr(userId);
14194            }
14195        }
14196    }
14197
14198    @GuardedBy("mPackages")
14199    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14200        if (isPackageDeviceAdmin(packageName, userId)) {
14201            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14202                    + "\": has an active device admin");
14203            return false;
14204        }
14205
14206        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14207        if (packageName.equals(activeLauncherPackageName)) {
14208            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14209                    + "\": contains the active launcher");
14210            return false;
14211        }
14212
14213        if (packageName.equals(mRequiredInstallerPackage)) {
14214            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14215                    + "\": required for package installation");
14216            return false;
14217        }
14218
14219        if (packageName.equals(mRequiredUninstallerPackage)) {
14220            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14221                    + "\": required for package uninstallation");
14222            return false;
14223        }
14224
14225        if (packageName.equals(mRequiredVerifierPackage)) {
14226            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14227                    + "\": required for package verification");
14228            return false;
14229        }
14230
14231        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14232            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14233                    + "\": is the default dialer");
14234            return false;
14235        }
14236
14237        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14238            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14239                    + "\": protected package");
14240            return false;
14241        }
14242
14243        // Cannot suspend static shared libs as they are considered
14244        // a part of the using app (emulating static linking). Also
14245        // static libs are installed always on internal storage.
14246        PackageParser.Package pkg = mPackages.get(packageName);
14247        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14248            Slog.w(TAG, "Cannot suspend package: " + packageName
14249                    + " providing static shared library: "
14250                    + pkg.staticSharedLibName);
14251            return false;
14252        }
14253
14254        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14255            Slog.w(TAG, "Cannot suspend package: " + packageName);
14256            return false;
14257        }
14258
14259        return true;
14260    }
14261
14262    private String getActiveLauncherPackageName(int userId) {
14263        Intent intent = new Intent(Intent.ACTION_MAIN);
14264        intent.addCategory(Intent.CATEGORY_HOME);
14265        ResolveInfo resolveInfo = resolveIntent(
14266                intent,
14267                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14268                PackageManager.MATCH_DEFAULT_ONLY,
14269                userId);
14270
14271        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14272    }
14273
14274    private String getDefaultDialerPackageName(int userId) {
14275        synchronized (mPackages) {
14276            return mSettings.getDefaultDialerPackageNameLPw(userId);
14277        }
14278    }
14279
14280    @Override
14281    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14282        mContext.enforceCallingOrSelfPermission(
14283                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14284                "Only package verification agents can verify applications");
14285
14286        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14287        final PackageVerificationResponse response = new PackageVerificationResponse(
14288                verificationCode, Binder.getCallingUid());
14289        msg.arg1 = id;
14290        msg.obj = response;
14291        mHandler.sendMessage(msg);
14292    }
14293
14294    @Override
14295    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14296            long millisecondsToDelay) {
14297        mContext.enforceCallingOrSelfPermission(
14298                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14299                "Only package verification agents can extend verification timeouts");
14300
14301        final PackageVerificationState state = mPendingVerification.get(id);
14302        final PackageVerificationResponse response = new PackageVerificationResponse(
14303                verificationCodeAtTimeout, Binder.getCallingUid());
14304
14305        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14306            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14307        }
14308        if (millisecondsToDelay < 0) {
14309            millisecondsToDelay = 0;
14310        }
14311        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14312                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14313            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14314        }
14315
14316        if ((state != null) && !state.timeoutExtended()) {
14317            state.extendTimeout();
14318
14319            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14320            msg.arg1 = id;
14321            msg.obj = response;
14322            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14323        }
14324    }
14325
14326    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14327            int verificationCode, UserHandle user) {
14328        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14329        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14330        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14331        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14332        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14333
14334        mContext.sendBroadcastAsUser(intent, user,
14335                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14336    }
14337
14338    private ComponentName matchComponentForVerifier(String packageName,
14339            List<ResolveInfo> receivers) {
14340        ActivityInfo targetReceiver = null;
14341
14342        final int NR = receivers.size();
14343        for (int i = 0; i < NR; i++) {
14344            final ResolveInfo info = receivers.get(i);
14345            if (info.activityInfo == null) {
14346                continue;
14347            }
14348
14349            if (packageName.equals(info.activityInfo.packageName)) {
14350                targetReceiver = info.activityInfo;
14351                break;
14352            }
14353        }
14354
14355        if (targetReceiver == null) {
14356            return null;
14357        }
14358
14359        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14360    }
14361
14362    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14363            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14364        if (pkgInfo.verifiers.length == 0) {
14365            return null;
14366        }
14367
14368        final int N = pkgInfo.verifiers.length;
14369        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14370        for (int i = 0; i < N; i++) {
14371            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14372
14373            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14374                    receivers);
14375            if (comp == null) {
14376                continue;
14377            }
14378
14379            final int verifierUid = getUidForVerifier(verifierInfo);
14380            if (verifierUid == -1) {
14381                continue;
14382            }
14383
14384            if (DEBUG_VERIFY) {
14385                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14386                        + " with the correct signature");
14387            }
14388            sufficientVerifiers.add(comp);
14389            verificationState.addSufficientVerifier(verifierUid);
14390        }
14391
14392        return sufficientVerifiers;
14393    }
14394
14395    private int getUidForVerifier(VerifierInfo verifierInfo) {
14396        synchronized (mPackages) {
14397            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14398            if (pkg == null) {
14399                return -1;
14400            } else if (pkg.mSigningDetails.signatures.length != 1) {
14401                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14402                        + " has more than one signature; ignoring");
14403                return -1;
14404            }
14405
14406            /*
14407             * If the public key of the package's signature does not match
14408             * our expected public key, then this is a different package and
14409             * we should skip.
14410             */
14411
14412            final byte[] expectedPublicKey;
14413            try {
14414                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14415                final PublicKey publicKey = verifierSig.getPublicKey();
14416                expectedPublicKey = publicKey.getEncoded();
14417            } catch (CertificateException e) {
14418                return -1;
14419            }
14420
14421            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14422
14423            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14424                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14425                        + " does not have the expected public key; ignoring");
14426                return -1;
14427            }
14428
14429            return pkg.applicationInfo.uid;
14430        }
14431    }
14432
14433    @Override
14434    public void finishPackageInstall(int token, boolean didLaunch) {
14435        enforceSystemOrRoot("Only the system is allowed to finish installs");
14436
14437        if (DEBUG_INSTALL) {
14438            Slog.v(TAG, "BM finishing package install for " + token);
14439        }
14440        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14441
14442        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14443        mHandler.sendMessage(msg);
14444    }
14445
14446    /**
14447     * Get the verification agent timeout.  Used for both the APK verifier and the
14448     * intent filter verifier.
14449     *
14450     * @return verification timeout in milliseconds
14451     */
14452    private long getVerificationTimeout() {
14453        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14454                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14455                DEFAULT_VERIFICATION_TIMEOUT);
14456    }
14457
14458    /**
14459     * Get the default verification agent response code.
14460     *
14461     * @return default verification response code
14462     */
14463    private int getDefaultVerificationResponse(UserHandle user) {
14464        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14465            return PackageManager.VERIFICATION_REJECT;
14466        }
14467        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14468                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14469                DEFAULT_VERIFICATION_RESPONSE);
14470    }
14471
14472    /**
14473     * Check whether or not package verification has been enabled.
14474     *
14475     * @return true if verification should be performed
14476     */
14477    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14478        if (!DEFAULT_VERIFY_ENABLE) {
14479            return false;
14480        }
14481
14482        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14483
14484        // Check if installing from ADB
14485        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14486            // Do not run verification in a test harness environment
14487            if (ActivityManager.isRunningInTestHarness()) {
14488                return false;
14489            }
14490            if (ensureVerifyAppsEnabled) {
14491                return true;
14492            }
14493            // Check if the developer does not want package verification for ADB installs
14494            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14495                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14496                return false;
14497            }
14498        } else {
14499            // only when not installed from ADB, skip verification for instant apps when
14500            // the installer and verifier are the same.
14501            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14502                if (mInstantAppInstallerActivity != null
14503                        && mInstantAppInstallerActivity.packageName.equals(
14504                                mRequiredVerifierPackage)) {
14505                    try {
14506                        mContext.getSystemService(AppOpsManager.class)
14507                                .checkPackage(installerUid, mRequiredVerifierPackage);
14508                        if (DEBUG_VERIFY) {
14509                            Slog.i(TAG, "disable verification for instant app");
14510                        }
14511                        return false;
14512                    } catch (SecurityException ignore) { }
14513                }
14514            }
14515        }
14516
14517        if (ensureVerifyAppsEnabled) {
14518            return true;
14519        }
14520
14521        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14522                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14523    }
14524
14525    @Override
14526    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14527            throws RemoteException {
14528        mContext.enforceCallingOrSelfPermission(
14529                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14530                "Only intentfilter verification agents can verify applications");
14531
14532        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14533        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14534                Binder.getCallingUid(), verificationCode, failedDomains);
14535        msg.arg1 = id;
14536        msg.obj = response;
14537        mHandler.sendMessage(msg);
14538    }
14539
14540    @Override
14541    public int getIntentVerificationStatus(String packageName, int userId) {
14542        final int callingUid = Binder.getCallingUid();
14543        if (UserHandle.getUserId(callingUid) != userId) {
14544            mContext.enforceCallingOrSelfPermission(
14545                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14546                    "getIntentVerificationStatus" + userId);
14547        }
14548        if (getInstantAppPackageName(callingUid) != null) {
14549            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14550        }
14551        synchronized (mPackages) {
14552            final PackageSetting ps = mSettings.mPackages.get(packageName);
14553            if (ps == null
14554                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14555                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14556            }
14557            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14558        }
14559    }
14560
14561    @Override
14562    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14563        mContext.enforceCallingOrSelfPermission(
14564                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14565
14566        boolean result = false;
14567        synchronized (mPackages) {
14568            final PackageSetting ps = mSettings.mPackages.get(packageName);
14569            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14570                return false;
14571            }
14572            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14573        }
14574        if (result) {
14575            scheduleWritePackageRestrictionsLocked(userId);
14576        }
14577        return result;
14578    }
14579
14580    @Override
14581    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14582            String packageName) {
14583        final int callingUid = Binder.getCallingUid();
14584        if (getInstantAppPackageName(callingUid) != null) {
14585            return ParceledListSlice.emptyList();
14586        }
14587        synchronized (mPackages) {
14588            final PackageSetting ps = mSettings.mPackages.get(packageName);
14589            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14590                return ParceledListSlice.emptyList();
14591            }
14592            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14593        }
14594    }
14595
14596    @Override
14597    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14598        if (TextUtils.isEmpty(packageName)) {
14599            return ParceledListSlice.emptyList();
14600        }
14601        final int callingUid = Binder.getCallingUid();
14602        final int callingUserId = UserHandle.getUserId(callingUid);
14603        synchronized (mPackages) {
14604            PackageParser.Package pkg = mPackages.get(packageName);
14605            if (pkg == null || pkg.activities == null) {
14606                return ParceledListSlice.emptyList();
14607            }
14608            if (pkg.mExtras == null) {
14609                return ParceledListSlice.emptyList();
14610            }
14611            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14612            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14613                return ParceledListSlice.emptyList();
14614            }
14615            final int count = pkg.activities.size();
14616            ArrayList<IntentFilter> result = new ArrayList<>();
14617            for (int n=0; n<count; n++) {
14618                PackageParser.Activity activity = pkg.activities.get(n);
14619                if (activity.intents != null && activity.intents.size() > 0) {
14620                    result.addAll(activity.intents);
14621                }
14622            }
14623            return new ParceledListSlice<>(result);
14624        }
14625    }
14626
14627    @Override
14628    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14629        mContext.enforceCallingOrSelfPermission(
14630                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14631        if (UserHandle.getCallingUserId() != userId) {
14632            mContext.enforceCallingOrSelfPermission(
14633                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14634        }
14635
14636        synchronized (mPackages) {
14637            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14638            if (packageName != null) {
14639                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14640                        packageName, userId);
14641            }
14642            return result;
14643        }
14644    }
14645
14646    @Override
14647    public String getDefaultBrowserPackageName(int userId) {
14648        if (UserHandle.getCallingUserId() != userId) {
14649            mContext.enforceCallingOrSelfPermission(
14650                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14651        }
14652        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14653            return null;
14654        }
14655        synchronized (mPackages) {
14656            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14657        }
14658    }
14659
14660    /**
14661     * Get the "allow unknown sources" setting.
14662     *
14663     * @return the current "allow unknown sources" setting
14664     */
14665    private int getUnknownSourcesSettings() {
14666        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14667                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14668                -1);
14669    }
14670
14671    @Override
14672    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14673        final int callingUid = Binder.getCallingUid();
14674        if (getInstantAppPackageName(callingUid) != null) {
14675            return;
14676        }
14677        // writer
14678        synchronized (mPackages) {
14679            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14680            if (targetPackageSetting == null
14681                    || filterAppAccessLPr(
14682                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14683                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14684            }
14685
14686            PackageSetting installerPackageSetting;
14687            if (installerPackageName != null) {
14688                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14689                if (installerPackageSetting == null) {
14690                    throw new IllegalArgumentException("Unknown installer package: "
14691                            + installerPackageName);
14692                }
14693            } else {
14694                installerPackageSetting = null;
14695            }
14696
14697            Signature[] callerSignature;
14698            Object obj = mSettings.getUserIdLPr(callingUid);
14699            if (obj != null) {
14700                if (obj instanceof SharedUserSetting) {
14701                    callerSignature =
14702                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14703                } else if (obj instanceof PackageSetting) {
14704                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14705                } else {
14706                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14707                }
14708            } else {
14709                throw new SecurityException("Unknown calling UID: " + callingUid);
14710            }
14711
14712            // Verify: can't set installerPackageName to a package that is
14713            // not signed with the same cert as the caller.
14714            if (installerPackageSetting != null) {
14715                if (compareSignatures(callerSignature,
14716                        installerPackageSetting.signatures.mSigningDetails.signatures)
14717                        != PackageManager.SIGNATURE_MATCH) {
14718                    throw new SecurityException(
14719                            "Caller does not have same cert as new installer package "
14720                            + installerPackageName);
14721                }
14722            }
14723
14724            // Verify: if target already has an installer package, it must
14725            // be signed with the same cert as the caller.
14726            if (targetPackageSetting.installerPackageName != null) {
14727                PackageSetting setting = mSettings.mPackages.get(
14728                        targetPackageSetting.installerPackageName);
14729                // If the currently set package isn't valid, then it's always
14730                // okay to change it.
14731                if (setting != null) {
14732                    if (compareSignatures(callerSignature,
14733                            setting.signatures.mSigningDetails.signatures)
14734                            != PackageManager.SIGNATURE_MATCH) {
14735                        throw new SecurityException(
14736                                "Caller does not have same cert as old installer package "
14737                                + targetPackageSetting.installerPackageName);
14738                    }
14739                }
14740            }
14741
14742            // Okay!
14743            targetPackageSetting.installerPackageName = installerPackageName;
14744            if (installerPackageName != null) {
14745                mSettings.mInstallerPackages.add(installerPackageName);
14746            }
14747            scheduleWriteSettingsLocked();
14748        }
14749    }
14750
14751    @Override
14752    public void setApplicationCategoryHint(String packageName, int categoryHint,
14753            String callerPackageName) {
14754        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14755            throw new SecurityException("Instant applications don't have access to this method");
14756        }
14757        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14758                callerPackageName);
14759        synchronized (mPackages) {
14760            PackageSetting ps = mSettings.mPackages.get(packageName);
14761            if (ps == null) {
14762                throw new IllegalArgumentException("Unknown target package " + packageName);
14763            }
14764            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14765                throw new IllegalArgumentException("Unknown target package " + packageName);
14766            }
14767            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14768                throw new IllegalArgumentException("Calling package " + callerPackageName
14769                        + " is not installer for " + packageName);
14770            }
14771
14772            if (ps.categoryHint != categoryHint) {
14773                ps.categoryHint = categoryHint;
14774                scheduleWriteSettingsLocked();
14775            }
14776        }
14777    }
14778
14779    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14780        // Queue up an async operation since the package installation may take a little while.
14781        mHandler.post(new Runnable() {
14782            public void run() {
14783                mHandler.removeCallbacks(this);
14784                 // Result object to be returned
14785                PackageInstalledInfo res = new PackageInstalledInfo();
14786                res.setReturnCode(currentStatus);
14787                res.uid = -1;
14788                res.pkg = null;
14789                res.removedInfo = null;
14790                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14791                    args.doPreInstall(res.returnCode);
14792                    synchronized (mInstallLock) {
14793                        installPackageTracedLI(args, res);
14794                    }
14795                    args.doPostInstall(res.returnCode, res.uid);
14796                }
14797
14798                // A restore should be performed at this point if (a) the install
14799                // succeeded, (b) the operation is not an update, and (c) the new
14800                // package has not opted out of backup participation.
14801                final boolean update = res.removedInfo != null
14802                        && res.removedInfo.removedPackage != null;
14803                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14804                boolean doRestore = !update
14805                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14806
14807                // Set up the post-install work request bookkeeping.  This will be used
14808                // and cleaned up by the post-install event handling regardless of whether
14809                // there's a restore pass performed.  Token values are >= 1.
14810                int token;
14811                if (mNextInstallToken < 0) mNextInstallToken = 1;
14812                token = mNextInstallToken++;
14813
14814                PostInstallData data = new PostInstallData(args, res);
14815                mRunningInstalls.put(token, data);
14816                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14817
14818                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14819                    // Pass responsibility to the Backup Manager.  It will perform a
14820                    // restore if appropriate, then pass responsibility back to the
14821                    // Package Manager to run the post-install observer callbacks
14822                    // and broadcasts.
14823                    IBackupManager bm = IBackupManager.Stub.asInterface(
14824                            ServiceManager.getService(Context.BACKUP_SERVICE));
14825                    if (bm != null) {
14826                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14827                                + " to BM for possible restore");
14828                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14829                        try {
14830                            // TODO: http://b/22388012
14831                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14832                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14833                            } else {
14834                                doRestore = false;
14835                            }
14836                        } catch (RemoteException e) {
14837                            // can't happen; the backup manager is local
14838                        } catch (Exception e) {
14839                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14840                            doRestore = false;
14841                        }
14842                    } else {
14843                        Slog.e(TAG, "Backup Manager not found!");
14844                        doRestore = false;
14845                    }
14846                }
14847
14848                if (!doRestore) {
14849                    // No restore possible, or the Backup Manager was mysteriously not
14850                    // available -- just fire the post-install work request directly.
14851                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14852
14853                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14854
14855                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14856                    mHandler.sendMessage(msg);
14857                }
14858            }
14859        });
14860    }
14861
14862    /**
14863     * Callback from PackageSettings whenever an app is first transitioned out of the
14864     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14865     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14866     * here whether the app is the target of an ongoing install, and only send the
14867     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14868     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14869     * handling.
14870     */
14871    void notifyFirstLaunch(final String packageName, final String installerPackage,
14872            final int userId) {
14873        // Serialize this with the rest of the install-process message chain.  In the
14874        // restore-at-install case, this Runnable will necessarily run before the
14875        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14876        // are coherent.  In the non-restore case, the app has already completed install
14877        // and been launched through some other means, so it is not in a problematic
14878        // state for observers to see the FIRST_LAUNCH signal.
14879        mHandler.post(new Runnable() {
14880            @Override
14881            public void run() {
14882                for (int i = 0; i < mRunningInstalls.size(); i++) {
14883                    final PostInstallData data = mRunningInstalls.valueAt(i);
14884                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14885                        continue;
14886                    }
14887                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14888                        // right package; but is it for the right user?
14889                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14890                            if (userId == data.res.newUsers[uIndex]) {
14891                                if (DEBUG_BACKUP) {
14892                                    Slog.i(TAG, "Package " + packageName
14893                                            + " being restored so deferring FIRST_LAUNCH");
14894                                }
14895                                return;
14896                            }
14897                        }
14898                    }
14899                }
14900                // didn't find it, so not being restored
14901                if (DEBUG_BACKUP) {
14902                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14903                }
14904                final boolean isInstantApp = isInstantApp(packageName, userId);
14905                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14906                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14907                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14908            }
14909        });
14910    }
14911
14912    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14913            int[] userIds, int[] instantUserIds) {
14914        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14915                installerPkg, null, userIds, instantUserIds);
14916    }
14917
14918    private abstract class HandlerParams {
14919        private static final int MAX_RETRIES = 4;
14920
14921        /**
14922         * Number of times startCopy() has been attempted and had a non-fatal
14923         * error.
14924         */
14925        private int mRetries = 0;
14926
14927        /** User handle for the user requesting the information or installation. */
14928        private final UserHandle mUser;
14929        String traceMethod;
14930        int traceCookie;
14931
14932        HandlerParams(UserHandle user) {
14933            mUser = user;
14934        }
14935
14936        UserHandle getUser() {
14937            return mUser;
14938        }
14939
14940        HandlerParams setTraceMethod(String traceMethod) {
14941            this.traceMethod = traceMethod;
14942            return this;
14943        }
14944
14945        HandlerParams setTraceCookie(int traceCookie) {
14946            this.traceCookie = traceCookie;
14947            return this;
14948        }
14949
14950        final boolean startCopy() {
14951            boolean res;
14952            try {
14953                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14954
14955                if (++mRetries > MAX_RETRIES) {
14956                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14957                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14958                    handleServiceError();
14959                    return false;
14960                } else {
14961                    handleStartCopy();
14962                    res = true;
14963                }
14964            } catch (RemoteException e) {
14965                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14966                mHandler.sendEmptyMessage(MCS_RECONNECT);
14967                res = false;
14968            }
14969            handleReturnCode();
14970            return res;
14971        }
14972
14973        final void serviceError() {
14974            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14975            handleServiceError();
14976            handleReturnCode();
14977        }
14978
14979        abstract void handleStartCopy() throws RemoteException;
14980        abstract void handleServiceError();
14981        abstract void handleReturnCode();
14982    }
14983
14984    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14985        for (File path : paths) {
14986            try {
14987                mcs.clearDirectory(path.getAbsolutePath());
14988            } catch (RemoteException e) {
14989            }
14990        }
14991    }
14992
14993    static class OriginInfo {
14994        /**
14995         * Location where install is coming from, before it has been
14996         * copied/renamed into place. This could be a single monolithic APK
14997         * file, or a cluster directory. This location may be untrusted.
14998         */
14999        final File file;
15000
15001        /**
15002         * Flag indicating that {@link #file} or {@link #cid} has already been
15003         * staged, meaning downstream users don't need to defensively copy the
15004         * contents.
15005         */
15006        final boolean staged;
15007
15008        /**
15009         * Flag indicating that {@link #file} or {@link #cid} is an already
15010         * installed app that is being moved.
15011         */
15012        final boolean existing;
15013
15014        final String resolvedPath;
15015        final File resolvedFile;
15016
15017        static OriginInfo fromNothing() {
15018            return new OriginInfo(null, false, false);
15019        }
15020
15021        static OriginInfo fromUntrustedFile(File file) {
15022            return new OriginInfo(file, false, false);
15023        }
15024
15025        static OriginInfo fromExistingFile(File file) {
15026            return new OriginInfo(file, false, true);
15027        }
15028
15029        static OriginInfo fromStagedFile(File file) {
15030            return new OriginInfo(file, true, false);
15031        }
15032
15033        private OriginInfo(File file, boolean staged, boolean existing) {
15034            this.file = file;
15035            this.staged = staged;
15036            this.existing = existing;
15037
15038            if (file != null) {
15039                resolvedPath = file.getAbsolutePath();
15040                resolvedFile = file;
15041            } else {
15042                resolvedPath = null;
15043                resolvedFile = null;
15044            }
15045        }
15046    }
15047
15048    static class MoveInfo {
15049        final int moveId;
15050        final String fromUuid;
15051        final String toUuid;
15052        final String packageName;
15053        final String dataAppName;
15054        final int appId;
15055        final String seinfo;
15056        final int targetSdkVersion;
15057
15058        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15059                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15060            this.moveId = moveId;
15061            this.fromUuid = fromUuid;
15062            this.toUuid = toUuid;
15063            this.packageName = packageName;
15064            this.dataAppName = dataAppName;
15065            this.appId = appId;
15066            this.seinfo = seinfo;
15067            this.targetSdkVersion = targetSdkVersion;
15068        }
15069    }
15070
15071    static class VerificationInfo {
15072        /** A constant used to indicate that a uid value is not present. */
15073        public static final int NO_UID = -1;
15074
15075        /** URI referencing where the package was downloaded from. */
15076        final Uri originatingUri;
15077
15078        /** HTTP referrer URI associated with the originatingURI. */
15079        final Uri referrer;
15080
15081        /** UID of the application that the install request originated from. */
15082        final int originatingUid;
15083
15084        /** UID of application requesting the install */
15085        final int installerUid;
15086
15087        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15088            this.originatingUri = originatingUri;
15089            this.referrer = referrer;
15090            this.originatingUid = originatingUid;
15091            this.installerUid = installerUid;
15092        }
15093    }
15094
15095    class InstallParams extends HandlerParams {
15096        final OriginInfo origin;
15097        final MoveInfo move;
15098        final IPackageInstallObserver2 observer;
15099        int installFlags;
15100        final String installerPackageName;
15101        final String volumeUuid;
15102        private InstallArgs mArgs;
15103        private int mRet;
15104        final String packageAbiOverride;
15105        final String[] grantedRuntimePermissions;
15106        final VerificationInfo verificationInfo;
15107        final PackageParser.SigningDetails signingDetails;
15108        final int installReason;
15109
15110        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15111                int installFlags, String installerPackageName, String volumeUuid,
15112                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15113                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15114            super(user);
15115            this.origin = origin;
15116            this.move = move;
15117            this.observer = observer;
15118            this.installFlags = installFlags;
15119            this.installerPackageName = installerPackageName;
15120            this.volumeUuid = volumeUuid;
15121            this.verificationInfo = verificationInfo;
15122            this.packageAbiOverride = packageAbiOverride;
15123            this.grantedRuntimePermissions = grantedPermissions;
15124            this.signingDetails = signingDetails;
15125            this.installReason = installReason;
15126        }
15127
15128        @Override
15129        public String toString() {
15130            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15131                    + " file=" + origin.file + "}";
15132        }
15133
15134        private int installLocationPolicy(PackageInfoLite pkgLite) {
15135            String packageName = pkgLite.packageName;
15136            int installLocation = pkgLite.installLocation;
15137            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15138            // reader
15139            synchronized (mPackages) {
15140                // Currently installed package which the new package is attempting to replace or
15141                // null if no such package is installed.
15142                PackageParser.Package installedPkg = mPackages.get(packageName);
15143                // Package which currently owns the data which the new package will own if installed.
15144                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15145                // will be null whereas dataOwnerPkg will contain information about the package
15146                // which was uninstalled while keeping its data.
15147                PackageParser.Package dataOwnerPkg = installedPkg;
15148                if (dataOwnerPkg  == null) {
15149                    PackageSetting ps = mSettings.mPackages.get(packageName);
15150                    if (ps != null) {
15151                        dataOwnerPkg = ps.pkg;
15152                    }
15153                }
15154
15155                if (dataOwnerPkg != null) {
15156                    // If installed, the package will get access to data left on the device by its
15157                    // predecessor. As a security measure, this is permited only if this is not a
15158                    // version downgrade or if the predecessor package is marked as debuggable and
15159                    // a downgrade is explicitly requested.
15160                    //
15161                    // On debuggable platform builds, downgrades are permitted even for
15162                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15163                    // not offer security guarantees and thus it's OK to disable some security
15164                    // mechanisms to make debugging/testing easier on those builds. However, even on
15165                    // debuggable builds downgrades of packages are permitted only if requested via
15166                    // installFlags. This is because we aim to keep the behavior of debuggable
15167                    // platform builds as close as possible to the behavior of non-debuggable
15168                    // platform builds.
15169                    final boolean downgradeRequested =
15170                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15171                    final boolean packageDebuggable =
15172                                (dataOwnerPkg.applicationInfo.flags
15173                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15174                    final boolean downgradePermitted =
15175                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15176                    if (!downgradePermitted) {
15177                        try {
15178                            checkDowngrade(dataOwnerPkg, pkgLite);
15179                        } catch (PackageManagerException e) {
15180                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15181                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15182                        }
15183                    }
15184                }
15185
15186                if (installedPkg != null) {
15187                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15188                        // Check for updated system application.
15189                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15190                            if (onSd) {
15191                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15192                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15193                            }
15194                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15195                        } else {
15196                            if (onSd) {
15197                                // Install flag overrides everything.
15198                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15199                            }
15200                            // If current upgrade specifies particular preference
15201                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15202                                // Application explicitly specified internal.
15203                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15204                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15205                                // App explictly prefers external. Let policy decide
15206                            } else {
15207                                // Prefer previous location
15208                                if (isExternal(installedPkg)) {
15209                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15210                                }
15211                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15212                            }
15213                        }
15214                    } else {
15215                        // Invalid install. Return error code
15216                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15217                    }
15218                }
15219            }
15220            // All the special cases have been taken care of.
15221            // Return result based on recommended install location.
15222            if (onSd) {
15223                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15224            }
15225            return pkgLite.recommendedInstallLocation;
15226        }
15227
15228        /*
15229         * Invoke remote method to get package information and install
15230         * location values. Override install location based on default
15231         * policy if needed and then create install arguments based
15232         * on the install location.
15233         */
15234        public void handleStartCopy() throws RemoteException {
15235            int ret = PackageManager.INSTALL_SUCCEEDED;
15236
15237            // If we're already staged, we've firmly committed to an install location
15238            if (origin.staged) {
15239                if (origin.file != null) {
15240                    installFlags |= PackageManager.INSTALL_INTERNAL;
15241                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15242                } else {
15243                    throw new IllegalStateException("Invalid stage location");
15244                }
15245            }
15246
15247            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15248            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15249            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15250            PackageInfoLite pkgLite = null;
15251
15252            if (onInt && onSd) {
15253                // Check if both bits are set.
15254                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15255                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15256            } else if (onSd && ephemeral) {
15257                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15258                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15259            } else {
15260                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15261                        packageAbiOverride);
15262
15263                if (DEBUG_INSTANT && ephemeral) {
15264                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15265                }
15266
15267                /*
15268                 * If we have too little free space, try to free cache
15269                 * before giving up.
15270                 */
15271                if (!origin.staged && pkgLite.recommendedInstallLocation
15272                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15273                    // TODO: focus freeing disk space on the target device
15274                    final StorageManager storage = StorageManager.from(mContext);
15275                    final long lowThreshold = storage.getStorageLowBytes(
15276                            Environment.getDataDirectory());
15277
15278                    final long sizeBytes = mContainerService.calculateInstalledSize(
15279                            origin.resolvedPath, packageAbiOverride);
15280
15281                    try {
15282                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15283                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15284                                installFlags, packageAbiOverride);
15285                    } catch (InstallerException e) {
15286                        Slog.w(TAG, "Failed to free cache", e);
15287                    }
15288
15289                    /*
15290                     * The cache free must have deleted the file we
15291                     * downloaded to install.
15292                     *
15293                     * TODO: fix the "freeCache" call to not delete
15294                     *       the file we care about.
15295                     */
15296                    if (pkgLite.recommendedInstallLocation
15297                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15298                        pkgLite.recommendedInstallLocation
15299                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15300                    }
15301                }
15302            }
15303
15304            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15305                int loc = pkgLite.recommendedInstallLocation;
15306                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15307                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15308                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15309                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15310                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15311                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15312                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15313                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15314                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15315                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15316                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15317                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15318                } else {
15319                    // Override with defaults if needed.
15320                    loc = installLocationPolicy(pkgLite);
15321                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15322                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15323                    } else if (!onSd && !onInt) {
15324                        // Override install location with flags
15325                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15326                            // Set the flag to install on external media.
15327                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15328                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15329                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15330                            if (DEBUG_INSTANT) {
15331                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15332                            }
15333                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15334                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15335                                    |PackageManager.INSTALL_INTERNAL);
15336                        } else {
15337                            // Make sure the flag for installing on external
15338                            // media is unset
15339                            installFlags |= PackageManager.INSTALL_INTERNAL;
15340                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15341                        }
15342                    }
15343                }
15344            }
15345
15346            final InstallArgs args = createInstallArgs(this);
15347            mArgs = args;
15348
15349            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15350                // TODO: http://b/22976637
15351                // Apps installed for "all" users use the device owner to verify the app
15352                UserHandle verifierUser = getUser();
15353                if (verifierUser == UserHandle.ALL) {
15354                    verifierUser = UserHandle.SYSTEM;
15355                }
15356
15357                /*
15358                 * Determine if we have any installed package verifiers. If we
15359                 * do, then we'll defer to them to verify the packages.
15360                 */
15361                final int requiredUid = mRequiredVerifierPackage == null ? -1
15362                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15363                                verifierUser.getIdentifier());
15364                final int installerUid =
15365                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15366                if (!origin.existing && requiredUid != -1
15367                        && isVerificationEnabled(
15368                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15369                    final Intent verification = new Intent(
15370                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15371                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15372                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15373                            PACKAGE_MIME_TYPE);
15374                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15375
15376                    // Query all live verifiers based on current user state
15377                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15378                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15379                            false /*allowDynamicSplits*/);
15380
15381                    if (DEBUG_VERIFY) {
15382                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15383                                + verification.toString() + " with " + pkgLite.verifiers.length
15384                                + " optional verifiers");
15385                    }
15386
15387                    final int verificationId = mPendingVerificationToken++;
15388
15389                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15390
15391                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15392                            installerPackageName);
15393
15394                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15395                            installFlags);
15396
15397                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15398                            pkgLite.packageName);
15399
15400                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15401                            pkgLite.versionCode);
15402
15403                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15404                            pkgLite.getLongVersionCode());
15405
15406                    if (verificationInfo != null) {
15407                        if (verificationInfo.originatingUri != null) {
15408                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15409                                    verificationInfo.originatingUri);
15410                        }
15411                        if (verificationInfo.referrer != null) {
15412                            verification.putExtra(Intent.EXTRA_REFERRER,
15413                                    verificationInfo.referrer);
15414                        }
15415                        if (verificationInfo.originatingUid >= 0) {
15416                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15417                                    verificationInfo.originatingUid);
15418                        }
15419                        if (verificationInfo.installerUid >= 0) {
15420                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15421                                    verificationInfo.installerUid);
15422                        }
15423                    }
15424
15425                    final PackageVerificationState verificationState = new PackageVerificationState(
15426                            requiredUid, args);
15427
15428                    mPendingVerification.append(verificationId, verificationState);
15429
15430                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15431                            receivers, verificationState);
15432
15433                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15434                    final long idleDuration = getVerificationTimeout();
15435
15436                    /*
15437                     * If any sufficient verifiers were listed in the package
15438                     * manifest, attempt to ask them.
15439                     */
15440                    if (sufficientVerifiers != null) {
15441                        final int N = sufficientVerifiers.size();
15442                        if (N == 0) {
15443                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15444                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15445                        } else {
15446                            for (int i = 0; i < N; i++) {
15447                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15448                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15449                                        verifierComponent.getPackageName(), idleDuration,
15450                                        verifierUser.getIdentifier(), false, "package verifier");
15451
15452                                final Intent sufficientIntent = new Intent(verification);
15453                                sufficientIntent.setComponent(verifierComponent);
15454                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15455                            }
15456                        }
15457                    }
15458
15459                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15460                            mRequiredVerifierPackage, receivers);
15461                    if (ret == PackageManager.INSTALL_SUCCEEDED
15462                            && mRequiredVerifierPackage != null) {
15463                        Trace.asyncTraceBegin(
15464                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15465                        /*
15466                         * Send the intent to the required verification agent,
15467                         * but only start the verification timeout after the
15468                         * target BroadcastReceivers have run.
15469                         */
15470                        verification.setComponent(requiredVerifierComponent);
15471                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15472                                mRequiredVerifierPackage, idleDuration,
15473                                verifierUser.getIdentifier(), false, "package verifier");
15474                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15475                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15476                                new BroadcastReceiver() {
15477                                    @Override
15478                                    public void onReceive(Context context, Intent intent) {
15479                                        final Message msg = mHandler
15480                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15481                                        msg.arg1 = verificationId;
15482                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15483                                    }
15484                                }, null, 0, null, null);
15485
15486                        /*
15487                         * We don't want the copy to proceed until verification
15488                         * succeeds, so null out this field.
15489                         */
15490                        mArgs = null;
15491                    }
15492                } else {
15493                    /*
15494                     * No package verification is enabled, so immediately start
15495                     * the remote call to initiate copy using temporary file.
15496                     */
15497                    ret = args.copyApk(mContainerService, true);
15498                }
15499            }
15500
15501            mRet = ret;
15502        }
15503
15504        @Override
15505        void handleReturnCode() {
15506            // If mArgs is null, then MCS couldn't be reached. When it
15507            // reconnects, it will try again to install. At that point, this
15508            // will succeed.
15509            if (mArgs != null) {
15510                processPendingInstall(mArgs, mRet);
15511            }
15512        }
15513
15514        @Override
15515        void handleServiceError() {
15516            mArgs = createInstallArgs(this);
15517            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15518        }
15519    }
15520
15521    private InstallArgs createInstallArgs(InstallParams params) {
15522        if (params.move != null) {
15523            return new MoveInstallArgs(params);
15524        } else {
15525            return new FileInstallArgs(params);
15526        }
15527    }
15528
15529    /**
15530     * Create args that describe an existing installed package. Typically used
15531     * when cleaning up old installs, or used as a move source.
15532     */
15533    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15534            String resourcePath, String[] instructionSets) {
15535        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15536    }
15537
15538    static abstract class InstallArgs {
15539        /** @see InstallParams#origin */
15540        final OriginInfo origin;
15541        /** @see InstallParams#move */
15542        final MoveInfo move;
15543
15544        final IPackageInstallObserver2 observer;
15545        // Always refers to PackageManager flags only
15546        final int installFlags;
15547        final String installerPackageName;
15548        final String volumeUuid;
15549        final UserHandle user;
15550        final String abiOverride;
15551        final String[] installGrantPermissions;
15552        /** If non-null, drop an async trace when the install completes */
15553        final String traceMethod;
15554        final int traceCookie;
15555        final PackageParser.SigningDetails signingDetails;
15556        final int installReason;
15557
15558        // The list of instruction sets supported by this app. This is currently
15559        // only used during the rmdex() phase to clean up resources. We can get rid of this
15560        // if we move dex files under the common app path.
15561        /* nullable */ String[] instructionSets;
15562
15563        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15564                int installFlags, String installerPackageName, String volumeUuid,
15565                UserHandle user, String[] instructionSets,
15566                String abiOverride, String[] installGrantPermissions,
15567                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15568                int installReason) {
15569            this.origin = origin;
15570            this.move = move;
15571            this.installFlags = installFlags;
15572            this.observer = observer;
15573            this.installerPackageName = installerPackageName;
15574            this.volumeUuid = volumeUuid;
15575            this.user = user;
15576            this.instructionSets = instructionSets;
15577            this.abiOverride = abiOverride;
15578            this.installGrantPermissions = installGrantPermissions;
15579            this.traceMethod = traceMethod;
15580            this.traceCookie = traceCookie;
15581            this.signingDetails = signingDetails;
15582            this.installReason = installReason;
15583        }
15584
15585        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15586        abstract int doPreInstall(int status);
15587
15588        /**
15589         * Rename package into final resting place. All paths on the given
15590         * scanned package should be updated to reflect the rename.
15591         */
15592        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15593        abstract int doPostInstall(int status, int uid);
15594
15595        /** @see PackageSettingBase#codePathString */
15596        abstract String getCodePath();
15597        /** @see PackageSettingBase#resourcePathString */
15598        abstract String getResourcePath();
15599
15600        // Need installer lock especially for dex file removal.
15601        abstract void cleanUpResourcesLI();
15602        abstract boolean doPostDeleteLI(boolean delete);
15603
15604        /**
15605         * Called before the source arguments are copied. This is used mostly
15606         * for MoveParams when it needs to read the source file to put it in the
15607         * destination.
15608         */
15609        int doPreCopy() {
15610            return PackageManager.INSTALL_SUCCEEDED;
15611        }
15612
15613        /**
15614         * Called after the source arguments are copied. This is used mostly for
15615         * MoveParams when it needs to read the source file to put it in the
15616         * destination.
15617         */
15618        int doPostCopy(int uid) {
15619            return PackageManager.INSTALL_SUCCEEDED;
15620        }
15621
15622        protected boolean isFwdLocked() {
15623            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15624        }
15625
15626        protected boolean isExternalAsec() {
15627            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15628        }
15629
15630        protected boolean isEphemeral() {
15631            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15632        }
15633
15634        UserHandle getUser() {
15635            return user;
15636        }
15637    }
15638
15639    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15640        if (!allCodePaths.isEmpty()) {
15641            if (instructionSets == null) {
15642                throw new IllegalStateException("instructionSet == null");
15643            }
15644            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15645            for (String codePath : allCodePaths) {
15646                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15647                    try {
15648                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15649                    } catch (InstallerException ignored) {
15650                    }
15651                }
15652            }
15653        }
15654    }
15655
15656    /**
15657     * Logic to handle installation of non-ASEC applications, including copying
15658     * and renaming logic.
15659     */
15660    class FileInstallArgs extends InstallArgs {
15661        private File codeFile;
15662        private File resourceFile;
15663
15664        // Example topology:
15665        // /data/app/com.example/base.apk
15666        // /data/app/com.example/split_foo.apk
15667        // /data/app/com.example/lib/arm/libfoo.so
15668        // /data/app/com.example/lib/arm64/libfoo.so
15669        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15670
15671        /** New install */
15672        FileInstallArgs(InstallParams params) {
15673            super(params.origin, params.move, params.observer, params.installFlags,
15674                    params.installerPackageName, params.volumeUuid,
15675                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15676                    params.grantedRuntimePermissions,
15677                    params.traceMethod, params.traceCookie, params.signingDetails,
15678                    params.installReason);
15679            if (isFwdLocked()) {
15680                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15681            }
15682        }
15683
15684        /** Existing install */
15685        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15686            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15687                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15688                    PackageManager.INSTALL_REASON_UNKNOWN);
15689            this.codeFile = (codePath != null) ? new File(codePath) : null;
15690            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15691        }
15692
15693        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15694            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15695            try {
15696                return doCopyApk(imcs, temp);
15697            } finally {
15698                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15699            }
15700        }
15701
15702        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15703            if (origin.staged) {
15704                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15705                codeFile = origin.file;
15706                resourceFile = origin.file;
15707                return PackageManager.INSTALL_SUCCEEDED;
15708            }
15709
15710            try {
15711                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15712                final File tempDir =
15713                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15714                codeFile = tempDir;
15715                resourceFile = tempDir;
15716            } catch (IOException e) {
15717                Slog.w(TAG, "Failed to create copy file: " + e);
15718                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15719            }
15720
15721            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15722                @Override
15723                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15724                    if (!FileUtils.isValidExtFilename(name)) {
15725                        throw new IllegalArgumentException("Invalid filename: " + name);
15726                    }
15727                    try {
15728                        final File file = new File(codeFile, name);
15729                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15730                                O_RDWR | O_CREAT, 0644);
15731                        Os.chmod(file.getAbsolutePath(), 0644);
15732                        return new ParcelFileDescriptor(fd);
15733                    } catch (ErrnoException e) {
15734                        throw new RemoteException("Failed to open: " + e.getMessage());
15735                    }
15736                }
15737            };
15738
15739            int ret = PackageManager.INSTALL_SUCCEEDED;
15740            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15741            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15742                Slog.e(TAG, "Failed to copy package");
15743                return ret;
15744            }
15745
15746            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15747            NativeLibraryHelper.Handle handle = null;
15748            try {
15749                handle = NativeLibraryHelper.Handle.create(codeFile);
15750                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15751                        abiOverride);
15752            } catch (IOException e) {
15753                Slog.e(TAG, "Copying native libraries failed", e);
15754                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15755            } finally {
15756                IoUtils.closeQuietly(handle);
15757            }
15758
15759            return ret;
15760        }
15761
15762        int doPreInstall(int status) {
15763            if (status != PackageManager.INSTALL_SUCCEEDED) {
15764                cleanUp();
15765            }
15766            return status;
15767        }
15768
15769        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15770            if (status != PackageManager.INSTALL_SUCCEEDED) {
15771                cleanUp();
15772                return false;
15773            }
15774
15775            final File targetDir = codeFile.getParentFile();
15776            final File beforeCodeFile = codeFile;
15777            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15778
15779            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15780            try {
15781                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15782            } catch (ErrnoException e) {
15783                Slog.w(TAG, "Failed to rename", e);
15784                return false;
15785            }
15786
15787            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15788                Slog.w(TAG, "Failed to restorecon");
15789                return false;
15790            }
15791
15792            // Reflect the rename internally
15793            codeFile = afterCodeFile;
15794            resourceFile = afterCodeFile;
15795
15796            // Reflect the rename in scanned details
15797            try {
15798                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15799            } catch (IOException e) {
15800                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15801                return false;
15802            }
15803            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15804                    afterCodeFile, pkg.baseCodePath));
15805            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15806                    afterCodeFile, pkg.splitCodePaths));
15807
15808            // Reflect the rename in app info
15809            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15810            pkg.setApplicationInfoCodePath(pkg.codePath);
15811            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15812            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15813            pkg.setApplicationInfoResourcePath(pkg.codePath);
15814            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15815            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15816
15817            return true;
15818        }
15819
15820        int doPostInstall(int status, int uid) {
15821            if (status != PackageManager.INSTALL_SUCCEEDED) {
15822                cleanUp();
15823            }
15824            return status;
15825        }
15826
15827        @Override
15828        String getCodePath() {
15829            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15830        }
15831
15832        @Override
15833        String getResourcePath() {
15834            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15835        }
15836
15837        private boolean cleanUp() {
15838            if (codeFile == null || !codeFile.exists()) {
15839                return false;
15840            }
15841
15842            removeCodePathLI(codeFile);
15843
15844            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15845                resourceFile.delete();
15846            }
15847
15848            return true;
15849        }
15850
15851        void cleanUpResourcesLI() {
15852            // Try enumerating all code paths before deleting
15853            List<String> allCodePaths = Collections.EMPTY_LIST;
15854            if (codeFile != null && codeFile.exists()) {
15855                try {
15856                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15857                    allCodePaths = pkg.getAllCodePaths();
15858                } catch (PackageParserException e) {
15859                    // Ignored; we tried our best
15860                }
15861            }
15862
15863            cleanUp();
15864            removeDexFiles(allCodePaths, instructionSets);
15865        }
15866
15867        boolean doPostDeleteLI(boolean delete) {
15868            // XXX err, shouldn't we respect the delete flag?
15869            cleanUpResourcesLI();
15870            return true;
15871        }
15872    }
15873
15874    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15875            PackageManagerException {
15876        if (copyRet < 0) {
15877            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15878                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15879                throw new PackageManagerException(copyRet, message);
15880            }
15881        }
15882    }
15883
15884    /**
15885     * Extract the StorageManagerService "container ID" from the full code path of an
15886     * .apk.
15887     */
15888    static String cidFromCodePath(String fullCodePath) {
15889        int eidx = fullCodePath.lastIndexOf("/");
15890        String subStr1 = fullCodePath.substring(0, eidx);
15891        int sidx = subStr1.lastIndexOf("/");
15892        return subStr1.substring(sidx+1, eidx);
15893    }
15894
15895    /**
15896     * Logic to handle movement of existing installed applications.
15897     */
15898    class MoveInstallArgs extends InstallArgs {
15899        private File codeFile;
15900        private File resourceFile;
15901
15902        /** New install */
15903        MoveInstallArgs(InstallParams params) {
15904            super(params.origin, params.move, params.observer, params.installFlags,
15905                    params.installerPackageName, params.volumeUuid,
15906                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15907                    params.grantedRuntimePermissions,
15908                    params.traceMethod, params.traceCookie, params.signingDetails,
15909                    params.installReason);
15910        }
15911
15912        int copyApk(IMediaContainerService imcs, boolean temp) {
15913            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15914                    + move.fromUuid + " to " + move.toUuid);
15915            synchronized (mInstaller) {
15916                try {
15917                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15918                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15919                } catch (InstallerException e) {
15920                    Slog.w(TAG, "Failed to move app", e);
15921                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15922                }
15923            }
15924
15925            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15926            resourceFile = codeFile;
15927            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15928
15929            return PackageManager.INSTALL_SUCCEEDED;
15930        }
15931
15932        int doPreInstall(int status) {
15933            if (status != PackageManager.INSTALL_SUCCEEDED) {
15934                cleanUp(move.toUuid);
15935            }
15936            return status;
15937        }
15938
15939        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15940            if (status != PackageManager.INSTALL_SUCCEEDED) {
15941                cleanUp(move.toUuid);
15942                return false;
15943            }
15944
15945            // Reflect the move in app info
15946            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15947            pkg.setApplicationInfoCodePath(pkg.codePath);
15948            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15949            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15950            pkg.setApplicationInfoResourcePath(pkg.codePath);
15951            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15952            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15953
15954            return true;
15955        }
15956
15957        int doPostInstall(int status, int uid) {
15958            if (status == PackageManager.INSTALL_SUCCEEDED) {
15959                cleanUp(move.fromUuid);
15960            } else {
15961                cleanUp(move.toUuid);
15962            }
15963            return status;
15964        }
15965
15966        @Override
15967        String getCodePath() {
15968            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15969        }
15970
15971        @Override
15972        String getResourcePath() {
15973            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15974        }
15975
15976        private boolean cleanUp(String volumeUuid) {
15977            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15978                    move.dataAppName);
15979            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15980            final int[] userIds = sUserManager.getUserIds();
15981            synchronized (mInstallLock) {
15982                // Clean up both app data and code
15983                // All package moves are frozen until finished
15984                for (int userId : userIds) {
15985                    try {
15986                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15987                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15988                    } catch (InstallerException e) {
15989                        Slog.w(TAG, String.valueOf(e));
15990                    }
15991                }
15992                removeCodePathLI(codeFile);
15993            }
15994            return true;
15995        }
15996
15997        void cleanUpResourcesLI() {
15998            throw new UnsupportedOperationException();
15999        }
16000
16001        boolean doPostDeleteLI(boolean delete) {
16002            throw new UnsupportedOperationException();
16003        }
16004    }
16005
16006    static String getAsecPackageName(String packageCid) {
16007        int idx = packageCid.lastIndexOf("-");
16008        if (idx == -1) {
16009            return packageCid;
16010        }
16011        return packageCid.substring(0, idx);
16012    }
16013
16014    // Utility method used to create code paths based on package name and available index.
16015    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16016        String idxStr = "";
16017        int idx = 1;
16018        // Fall back to default value of idx=1 if prefix is not
16019        // part of oldCodePath
16020        if (oldCodePath != null) {
16021            String subStr = oldCodePath;
16022            // Drop the suffix right away
16023            if (suffix != null && subStr.endsWith(suffix)) {
16024                subStr = subStr.substring(0, subStr.length() - suffix.length());
16025            }
16026            // If oldCodePath already contains prefix find out the
16027            // ending index to either increment or decrement.
16028            int sidx = subStr.lastIndexOf(prefix);
16029            if (sidx != -1) {
16030                subStr = subStr.substring(sidx + prefix.length());
16031                if (subStr != null) {
16032                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16033                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16034                    }
16035                    try {
16036                        idx = Integer.parseInt(subStr);
16037                        if (idx <= 1) {
16038                            idx++;
16039                        } else {
16040                            idx--;
16041                        }
16042                    } catch(NumberFormatException e) {
16043                    }
16044                }
16045            }
16046        }
16047        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16048        return prefix + idxStr;
16049    }
16050
16051    private File getNextCodePath(File targetDir, String packageName) {
16052        File result;
16053        SecureRandom random = new SecureRandom();
16054        byte[] bytes = new byte[16];
16055        do {
16056            random.nextBytes(bytes);
16057            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16058            result = new File(targetDir, packageName + "-" + suffix);
16059        } while (result.exists());
16060        return result;
16061    }
16062
16063    // Utility method that returns the relative package path with respect
16064    // to the installation directory. Like say for /data/data/com.test-1.apk
16065    // string com.test-1 is returned.
16066    static String deriveCodePathName(String codePath) {
16067        if (codePath == null) {
16068            return null;
16069        }
16070        final File codeFile = new File(codePath);
16071        final String name = codeFile.getName();
16072        if (codeFile.isDirectory()) {
16073            return name;
16074        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16075            final int lastDot = name.lastIndexOf('.');
16076            return name.substring(0, lastDot);
16077        } else {
16078            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16079            return null;
16080        }
16081    }
16082
16083    static class PackageInstalledInfo {
16084        String name;
16085        int uid;
16086        // The set of users that originally had this package installed.
16087        int[] origUsers;
16088        // The set of users that now have this package installed.
16089        int[] newUsers;
16090        PackageParser.Package pkg;
16091        int returnCode;
16092        String returnMsg;
16093        String installerPackageName;
16094        PackageRemovedInfo removedInfo;
16095        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16096
16097        public void setError(int code, String msg) {
16098            setReturnCode(code);
16099            setReturnMessage(msg);
16100            Slog.w(TAG, msg);
16101        }
16102
16103        public void setError(String msg, PackageParserException e) {
16104            setReturnCode(e.error);
16105            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16106            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16107            for (int i = 0; i < childCount; i++) {
16108                addedChildPackages.valueAt(i).setError(msg, e);
16109            }
16110            Slog.w(TAG, msg, e);
16111        }
16112
16113        public void setError(String msg, PackageManagerException e) {
16114            returnCode = e.error;
16115            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16116            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16117            for (int i = 0; i < childCount; i++) {
16118                addedChildPackages.valueAt(i).setError(msg, e);
16119            }
16120            Slog.w(TAG, msg, e);
16121        }
16122
16123        public void setReturnCode(int returnCode) {
16124            this.returnCode = returnCode;
16125            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16126            for (int i = 0; i < childCount; i++) {
16127                addedChildPackages.valueAt(i).returnCode = returnCode;
16128            }
16129        }
16130
16131        private void setReturnMessage(String returnMsg) {
16132            this.returnMsg = returnMsg;
16133            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16134            for (int i = 0; i < childCount; i++) {
16135                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16136            }
16137        }
16138
16139        // In some error cases we want to convey more info back to the observer
16140        String origPackage;
16141        String origPermission;
16142    }
16143
16144    /*
16145     * Install a non-existing package.
16146     */
16147    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16148            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16149            String volumeUuid, PackageInstalledInfo res, int installReason) {
16150        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16151
16152        // Remember this for later, in case we need to rollback this install
16153        String pkgName = pkg.packageName;
16154
16155        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16156
16157        synchronized(mPackages) {
16158            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16159            if (renamedPackage != null) {
16160                // A package with the same name is already installed, though
16161                // it has been renamed to an older name.  The package we
16162                // are trying to install should be installed as an update to
16163                // the existing one, but that has not been requested, so bail.
16164                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16165                        + " without first uninstalling package running as "
16166                        + renamedPackage);
16167                return;
16168            }
16169            if (mPackages.containsKey(pkgName)) {
16170                // Don't allow installation over an existing package with the same name.
16171                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16172                        + " without first uninstalling.");
16173                return;
16174            }
16175        }
16176
16177        try {
16178            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16179                    System.currentTimeMillis(), user);
16180
16181            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16182
16183            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16184                prepareAppDataAfterInstallLIF(newPackage);
16185
16186            } else {
16187                // Remove package from internal structures, but keep around any
16188                // data that might have already existed
16189                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16190                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16191            }
16192        } catch (PackageManagerException e) {
16193            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16194        }
16195
16196        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16197    }
16198
16199    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16200        try (DigestInputStream digestStream =
16201                new DigestInputStream(new FileInputStream(file), digest)) {
16202            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16203        }
16204    }
16205
16206    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16207            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16208            PackageInstalledInfo res, int installReason) {
16209        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16210
16211        final PackageParser.Package oldPackage;
16212        final PackageSetting ps;
16213        final String pkgName = pkg.packageName;
16214        final int[] allUsers;
16215        final int[] installedUsers;
16216
16217        synchronized(mPackages) {
16218            oldPackage = mPackages.get(pkgName);
16219            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16220
16221            // don't allow upgrade to target a release SDK from a pre-release SDK
16222            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16223                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16224            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16225                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16226            if (oldTargetsPreRelease
16227                    && !newTargetsPreRelease
16228                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16229                Slog.w(TAG, "Can't install package targeting released sdk");
16230                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16231                return;
16232            }
16233
16234            ps = mSettings.mPackages.get(pkgName);
16235
16236            // verify signatures are valid
16237            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16238            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16239                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16240                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16241                            "New package not signed by keys specified by upgrade-keysets: "
16242                                    + pkgName);
16243                    return;
16244                }
16245            } else {
16246
16247                // default to original signature matching
16248                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16249                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16250                                && !oldPackage.mSigningDetails.checkCapability(
16251                                        pkg.mSigningDetails,
16252                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16253                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16254                            "New package has a different signature: " + pkgName);
16255                    return;
16256                }
16257            }
16258
16259            // don't allow a system upgrade unless the upgrade hash matches
16260            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16261                byte[] digestBytes = null;
16262                try {
16263                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16264                    updateDigest(digest, new File(pkg.baseCodePath));
16265                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16266                        for (String path : pkg.splitCodePaths) {
16267                            updateDigest(digest, new File(path));
16268                        }
16269                    }
16270                    digestBytes = digest.digest();
16271                } catch (NoSuchAlgorithmException | IOException e) {
16272                    res.setError(INSTALL_FAILED_INVALID_APK,
16273                            "Could not compute hash: " + pkgName);
16274                    return;
16275                }
16276                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16277                    res.setError(INSTALL_FAILED_INVALID_APK,
16278                            "New package fails restrict-update check: " + pkgName);
16279                    return;
16280                }
16281                // retain upgrade restriction
16282                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16283            }
16284
16285            // Check for shared user id changes
16286            String invalidPackageName =
16287                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16288            if (invalidPackageName != null) {
16289                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16290                        "Package " + invalidPackageName + " tried to change user "
16291                                + oldPackage.mSharedUserId);
16292                return;
16293            }
16294
16295            // check if the new package supports all of the abis which the old package supports
16296            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16297            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16298            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16299                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16300                        "Update to package " + pkgName + " doesn't support multi arch");
16301                return;
16302            }
16303
16304            // In case of rollback, remember per-user/profile install state
16305            allUsers = sUserManager.getUserIds();
16306            installedUsers = ps.queryInstalledUsers(allUsers, true);
16307
16308            // don't allow an upgrade from full to ephemeral
16309            if (isInstantApp) {
16310                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16311                    for (int currentUser : allUsers) {
16312                        if (!ps.getInstantApp(currentUser)) {
16313                            // can't downgrade from full to instant
16314                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16315                                    + " for user: " + currentUser);
16316                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16317                            return;
16318                        }
16319                    }
16320                } else if (!ps.getInstantApp(user.getIdentifier())) {
16321                    // can't downgrade from full to instant
16322                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16323                            + " for user: " + user.getIdentifier());
16324                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16325                    return;
16326                }
16327            }
16328        }
16329
16330        // Update what is removed
16331        res.removedInfo = new PackageRemovedInfo(this);
16332        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16333        res.removedInfo.removedPackage = oldPackage.packageName;
16334        res.removedInfo.installerPackageName = ps.installerPackageName;
16335        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16336        res.removedInfo.isUpdate = true;
16337        res.removedInfo.origUsers = installedUsers;
16338        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16339        for (int i = 0; i < installedUsers.length; i++) {
16340            final int userId = installedUsers[i];
16341            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16342        }
16343
16344        final int childCount = (oldPackage.childPackages != null)
16345                ? oldPackage.childPackages.size() : 0;
16346        for (int i = 0; i < childCount; i++) {
16347            boolean childPackageUpdated = false;
16348            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16349            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16350            if (res.addedChildPackages != null) {
16351                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16352                if (childRes != null) {
16353                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16354                    childRes.removedInfo.removedPackage = childPkg.packageName;
16355                    if (childPs != null) {
16356                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16357                    }
16358                    childRes.removedInfo.isUpdate = true;
16359                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16360                    childPackageUpdated = true;
16361                }
16362            }
16363            if (!childPackageUpdated) {
16364                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16365                childRemovedRes.removedPackage = childPkg.packageName;
16366                if (childPs != null) {
16367                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16368                }
16369                childRemovedRes.isUpdate = false;
16370                childRemovedRes.dataRemoved = true;
16371                synchronized (mPackages) {
16372                    if (childPs != null) {
16373                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16374                    }
16375                }
16376                if (res.removedInfo.removedChildPackages == null) {
16377                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16378                }
16379                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16380            }
16381        }
16382
16383        boolean sysPkg = (isSystemApp(oldPackage));
16384        if (sysPkg) {
16385            // Set the system/privileged/oem/vendor/product flags as needed
16386            final boolean privileged =
16387                    (oldPackage.applicationInfo.privateFlags
16388                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16389            final boolean oem =
16390                    (oldPackage.applicationInfo.privateFlags
16391                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16392            final boolean vendor =
16393                    (oldPackage.applicationInfo.privateFlags
16394                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16395            final boolean product =
16396                    (oldPackage.applicationInfo.privateFlags
16397                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16398            final @ParseFlags int systemParseFlags = parseFlags;
16399            final @ScanFlags int systemScanFlags = scanFlags
16400                    | SCAN_AS_SYSTEM
16401                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16402                    | (oem ? SCAN_AS_OEM : 0)
16403                    | (vendor ? SCAN_AS_VENDOR : 0)
16404                    | (product ? SCAN_AS_PRODUCT : 0);
16405
16406            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16407                    user, allUsers, installerPackageName, res, installReason);
16408        } else {
16409            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16410                    user, allUsers, installerPackageName, res, installReason);
16411        }
16412    }
16413
16414    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16415            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16416            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16417            String installerPackageName, PackageInstalledInfo res, int installReason) {
16418        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16419                + deletedPackage);
16420
16421        String pkgName = deletedPackage.packageName;
16422        boolean deletedPkg = true;
16423        boolean addedPkg = false;
16424        boolean updatedSettings = false;
16425        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16426        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16427                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16428
16429        final long origUpdateTime = (pkg.mExtras != null)
16430                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16431
16432        // First delete the existing package while retaining the data directory
16433        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16434                res.removedInfo, true, pkg)) {
16435            // If the existing package wasn't successfully deleted
16436            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16437            deletedPkg = false;
16438        } else {
16439            // Successfully deleted the old package; proceed with replace.
16440
16441            // If deleted package lived in a container, give users a chance to
16442            // relinquish resources before killing.
16443            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16444                if (DEBUG_INSTALL) {
16445                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16446                }
16447                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16448                final ArrayList<String> pkgList = new ArrayList<String>(1);
16449                pkgList.add(deletedPackage.applicationInfo.packageName);
16450                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16451            }
16452
16453            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16454                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16455
16456            try {
16457                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16458                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16459                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16460                        installReason);
16461
16462                // Update the in-memory copy of the previous code paths.
16463                PackageSetting ps = mSettings.mPackages.get(pkgName);
16464                if (!killApp) {
16465                    if (ps.oldCodePaths == null) {
16466                        ps.oldCodePaths = new ArraySet<>();
16467                    }
16468                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16469                    if (deletedPackage.splitCodePaths != null) {
16470                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16471                    }
16472                } else {
16473                    ps.oldCodePaths = null;
16474                }
16475                if (ps.childPackageNames != null) {
16476                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16477                        final String childPkgName = ps.childPackageNames.get(i);
16478                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16479                        childPs.oldCodePaths = ps.oldCodePaths;
16480                    }
16481                }
16482                prepareAppDataAfterInstallLIF(newPackage);
16483                addedPkg = true;
16484                mDexManager.notifyPackageUpdated(newPackage.packageName,
16485                        newPackage.baseCodePath, newPackage.splitCodePaths);
16486            } catch (PackageManagerException e) {
16487                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16488            }
16489        }
16490
16491        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16492            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16493
16494            // Revert all internal state mutations and added folders for the failed install
16495            if (addedPkg) {
16496                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16497                        res.removedInfo, true, null);
16498            }
16499
16500            // Restore the old package
16501            if (deletedPkg) {
16502                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16503                File restoreFile = new File(deletedPackage.codePath);
16504                // Parse old package
16505                boolean oldExternal = isExternal(deletedPackage);
16506                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16507                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16508                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16509                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16510                try {
16511                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16512                            null);
16513                } catch (PackageManagerException e) {
16514                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16515                            + e.getMessage());
16516                    return;
16517                }
16518
16519                synchronized (mPackages) {
16520                    // Ensure the installer package name up to date
16521                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16522
16523                    // Update permissions for restored package
16524                    mPermissionManager.updatePermissions(
16525                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16526                            mPermissionCallback);
16527
16528                    mSettings.writeLPr();
16529                }
16530
16531                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16532            }
16533        } else {
16534            synchronized (mPackages) {
16535                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16536                if (ps != null) {
16537                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16538                    if (res.removedInfo.removedChildPackages != null) {
16539                        final int childCount = res.removedInfo.removedChildPackages.size();
16540                        // Iterate in reverse as we may modify the collection
16541                        for (int i = childCount - 1; i >= 0; i--) {
16542                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16543                            if (res.addedChildPackages.containsKey(childPackageName)) {
16544                                res.removedInfo.removedChildPackages.removeAt(i);
16545                            } else {
16546                                PackageRemovedInfo childInfo = res.removedInfo
16547                                        .removedChildPackages.valueAt(i);
16548                                childInfo.removedForAllUsers = mPackages.get(
16549                                        childInfo.removedPackage) == null;
16550                            }
16551                        }
16552                    }
16553                }
16554            }
16555        }
16556    }
16557
16558    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16559            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16560            final @ScanFlags int scanFlags, UserHandle user,
16561            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16562            int installReason) {
16563        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16564                + ", old=" + deletedPackage);
16565
16566        final boolean disabledSystem;
16567
16568        // Remove existing system package
16569        removePackageLI(deletedPackage, true);
16570
16571        synchronized (mPackages) {
16572            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16573        }
16574        if (!disabledSystem) {
16575            // We didn't need to disable the .apk as a current system package,
16576            // which means we are replacing another update that is already
16577            // installed.  We need to make sure to delete the older one's .apk.
16578            res.removedInfo.args = createInstallArgsForExisting(0,
16579                    deletedPackage.applicationInfo.getCodePath(),
16580                    deletedPackage.applicationInfo.getResourcePath(),
16581                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16582        } else {
16583            res.removedInfo.args = null;
16584        }
16585
16586        // Successfully disabled the old package. Now proceed with re-installation
16587        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16588                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16589
16590        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16591        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16592                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16593
16594        PackageParser.Package newPackage = null;
16595        try {
16596            // Add the package to the internal data structures
16597            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16598
16599            // Set the update and install times
16600            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16601            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16602                    System.currentTimeMillis());
16603
16604            // Update the package dynamic state if succeeded
16605            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16606                // Now that the install succeeded make sure we remove data
16607                // directories for any child package the update removed.
16608                final int deletedChildCount = (deletedPackage.childPackages != null)
16609                        ? deletedPackage.childPackages.size() : 0;
16610                final int newChildCount = (newPackage.childPackages != null)
16611                        ? newPackage.childPackages.size() : 0;
16612                for (int i = 0; i < deletedChildCount; i++) {
16613                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16614                    boolean childPackageDeleted = true;
16615                    for (int j = 0; j < newChildCount; j++) {
16616                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16617                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16618                            childPackageDeleted = false;
16619                            break;
16620                        }
16621                    }
16622                    if (childPackageDeleted) {
16623                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16624                                deletedChildPkg.packageName);
16625                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16626                            PackageRemovedInfo removedChildRes = res.removedInfo
16627                                    .removedChildPackages.get(deletedChildPkg.packageName);
16628                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16629                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16630                        }
16631                    }
16632                }
16633
16634                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16635                        installReason);
16636                prepareAppDataAfterInstallLIF(newPackage);
16637
16638                mDexManager.notifyPackageUpdated(newPackage.packageName,
16639                            newPackage.baseCodePath, newPackage.splitCodePaths);
16640            }
16641        } catch (PackageManagerException e) {
16642            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16643            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16644        }
16645
16646        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16647            // Re installation failed. Restore old information
16648            // Remove new pkg information
16649            if (newPackage != null) {
16650                removeInstalledPackageLI(newPackage, true);
16651            }
16652            // Add back the old system package
16653            try {
16654                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16655            } catch (PackageManagerException e) {
16656                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16657            }
16658
16659            synchronized (mPackages) {
16660                if (disabledSystem) {
16661                    enableSystemPackageLPw(deletedPackage);
16662                }
16663
16664                // Ensure the installer package name up to date
16665                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16666
16667                // Update permissions for restored package
16668                mPermissionManager.updatePermissions(
16669                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16670                        mPermissionCallback);
16671
16672                mSettings.writeLPr();
16673            }
16674
16675            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16676                    + " after failed upgrade");
16677        }
16678    }
16679
16680    /**
16681     * Checks whether the parent or any of the child packages have a change shared
16682     * user. For a package to be a valid update the shred users of the parent and
16683     * the children should match. We may later support changing child shared users.
16684     * @param oldPkg The updated package.
16685     * @param newPkg The update package.
16686     * @return The shared user that change between the versions.
16687     */
16688    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16689            PackageParser.Package newPkg) {
16690        // Check parent shared user
16691        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16692            return newPkg.packageName;
16693        }
16694        // Check child shared users
16695        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16696        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16697        for (int i = 0; i < newChildCount; i++) {
16698            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16699            // If this child was present, did it have the same shared user?
16700            for (int j = 0; j < oldChildCount; j++) {
16701                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16702                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16703                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16704                    return newChildPkg.packageName;
16705                }
16706            }
16707        }
16708        return null;
16709    }
16710
16711    private void removeNativeBinariesLI(PackageSetting ps) {
16712        // Remove the lib path for the parent package
16713        if (ps != null) {
16714            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16715            // Remove the lib path for the child packages
16716            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16717            for (int i = 0; i < childCount; i++) {
16718                PackageSetting childPs = null;
16719                synchronized (mPackages) {
16720                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16721                }
16722                if (childPs != null) {
16723                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16724                            .legacyNativeLibraryPathString);
16725                }
16726            }
16727        }
16728    }
16729
16730    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16731        // Enable the parent package
16732        mSettings.enableSystemPackageLPw(pkg.packageName);
16733        // Enable the child packages
16734        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16735        for (int i = 0; i < childCount; i++) {
16736            PackageParser.Package childPkg = pkg.childPackages.get(i);
16737            mSettings.enableSystemPackageLPw(childPkg.packageName);
16738        }
16739    }
16740
16741    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16742            PackageParser.Package newPkg) {
16743        // Disable the parent package (parent always replaced)
16744        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16745        // Disable the child packages
16746        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16747        for (int i = 0; i < childCount; i++) {
16748            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16749            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16750            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16751        }
16752        return disabled;
16753    }
16754
16755    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16756            String installerPackageName) {
16757        // Enable the parent package
16758        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16759        // Enable the child packages
16760        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16761        for (int i = 0; i < childCount; i++) {
16762            PackageParser.Package childPkg = pkg.childPackages.get(i);
16763            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16764        }
16765    }
16766
16767    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16768            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16769        // Update the parent package setting
16770        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16771                res, user, installReason);
16772        // Update the child packages setting
16773        final int childCount = (newPackage.childPackages != null)
16774                ? newPackage.childPackages.size() : 0;
16775        for (int i = 0; i < childCount; i++) {
16776            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16777            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16778            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16779                    childRes.origUsers, childRes, user, installReason);
16780        }
16781    }
16782
16783    private void updateSettingsInternalLI(PackageParser.Package pkg,
16784            String installerPackageName, int[] allUsers, int[] installedForUsers,
16785            PackageInstalledInfo res, UserHandle user, int installReason) {
16786        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16787
16788        final String pkgName = pkg.packageName;
16789
16790        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16791        synchronized (mPackages) {
16792// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16793            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16794                    mPermissionCallback);
16795            // For system-bundled packages, we assume that installing an upgraded version
16796            // of the package implies that the user actually wants to run that new code,
16797            // so we enable the package.
16798            PackageSetting ps = mSettings.mPackages.get(pkgName);
16799            final int userId = user.getIdentifier();
16800            if (ps != null) {
16801                if (isSystemApp(pkg)) {
16802                    if (DEBUG_INSTALL) {
16803                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16804                    }
16805                    // Enable system package for requested users
16806                    if (res.origUsers != null) {
16807                        for (int origUserId : res.origUsers) {
16808                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16809                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16810                                        origUserId, installerPackageName);
16811                            }
16812                        }
16813                    }
16814                    // Also convey the prior install/uninstall state
16815                    if (allUsers != null && installedForUsers != null) {
16816                        for (int currentUserId : allUsers) {
16817                            final boolean installed = ArrayUtils.contains(
16818                                    installedForUsers, currentUserId);
16819                            if (DEBUG_INSTALL) {
16820                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16821                            }
16822                            ps.setInstalled(installed, currentUserId);
16823                        }
16824                        // these install state changes will be persisted in the
16825                        // upcoming call to mSettings.writeLPr().
16826                    }
16827                }
16828                // It's implied that when a user requests installation, they want the app to be
16829                // installed and enabled.
16830                if (userId != UserHandle.USER_ALL) {
16831                    ps.setInstalled(true, userId);
16832                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16833                }
16834
16835                // When replacing an existing package, preserve the original install reason for all
16836                // users that had the package installed before.
16837                final Set<Integer> previousUserIds = new ArraySet<>();
16838                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16839                    final int installReasonCount = res.removedInfo.installReasons.size();
16840                    for (int i = 0; i < installReasonCount; i++) {
16841                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16842                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16843                        ps.setInstallReason(previousInstallReason, previousUserId);
16844                        previousUserIds.add(previousUserId);
16845                    }
16846                }
16847
16848                // Set install reason for users that are having the package newly installed.
16849                if (userId == UserHandle.USER_ALL) {
16850                    for (int currentUserId : sUserManager.getUserIds()) {
16851                        if (!previousUserIds.contains(currentUserId)) {
16852                            ps.setInstallReason(installReason, currentUserId);
16853                        }
16854                    }
16855                } else if (!previousUserIds.contains(userId)) {
16856                    ps.setInstallReason(installReason, userId);
16857                }
16858                mSettings.writeKernelMappingLPr(ps);
16859            }
16860            res.name = pkgName;
16861            res.uid = pkg.applicationInfo.uid;
16862            res.pkg = pkg;
16863            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16864            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16865            //to update install status
16866            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16867            mSettings.writeLPr();
16868            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16869        }
16870
16871        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16872    }
16873
16874    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16875        try {
16876            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16877            installPackageLI(args, res);
16878        } finally {
16879            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16880        }
16881    }
16882
16883    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16884        final int installFlags = args.installFlags;
16885        final String installerPackageName = args.installerPackageName;
16886        final String volumeUuid = args.volumeUuid;
16887        final File tmpPackageFile = new File(args.getCodePath());
16888        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16889        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16890                || (args.volumeUuid != null));
16891        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16892        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16893        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16894        final boolean virtualPreload =
16895                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16896        boolean replace = false;
16897        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16898        if (args.move != null) {
16899            // moving a complete application; perform an initial scan on the new install location
16900            scanFlags |= SCAN_INITIAL;
16901        }
16902        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16903            scanFlags |= SCAN_DONT_KILL_APP;
16904        }
16905        if (instantApp) {
16906            scanFlags |= SCAN_AS_INSTANT_APP;
16907        }
16908        if (fullApp) {
16909            scanFlags |= SCAN_AS_FULL_APP;
16910        }
16911        if (virtualPreload) {
16912            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16913        }
16914
16915        // Result object to be returned
16916        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16917        res.installerPackageName = installerPackageName;
16918
16919        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16920
16921        // Sanity check
16922        if (instantApp && (forwardLocked || onExternal)) {
16923            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16924                    + " external=" + onExternal);
16925            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16926            return;
16927        }
16928
16929        // Retrieve PackageSettings and parse package
16930        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16931                | PackageParser.PARSE_ENFORCE_CODE
16932                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16933                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16934                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16935        PackageParser pp = new PackageParser();
16936        pp.setSeparateProcesses(mSeparateProcesses);
16937        pp.setDisplayMetrics(mMetrics);
16938        pp.setCallback(mPackageParserCallback);
16939
16940        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16941        final PackageParser.Package pkg;
16942        try {
16943            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16944            DexMetadataHelper.validatePackageDexMetadata(pkg);
16945        } catch (PackageParserException e) {
16946            res.setError("Failed parse during installPackageLI", e);
16947            return;
16948        } finally {
16949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16950        }
16951
16952        // Instant apps have several additional install-time checks.
16953        if (instantApp) {
16954            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16955                Slog.w(TAG,
16956                        "Instant app package " + pkg.packageName + " does not target at least O");
16957                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16958                        "Instant app package must target at least O");
16959                return;
16960            }
16961            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16962                Slog.w(TAG, "Instant app package " + pkg.packageName
16963                        + " does not target targetSandboxVersion 2");
16964                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16965                        "Instant app package must use targetSandboxVersion 2");
16966                return;
16967            }
16968            if (pkg.mSharedUserId != null) {
16969                Slog.w(TAG, "Instant app package " + pkg.packageName
16970                        + " may not declare sharedUserId.");
16971                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16972                        "Instant app package may not declare a sharedUserId");
16973                return;
16974            }
16975        }
16976
16977        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16978            // Static shared libraries have synthetic package names
16979            renameStaticSharedLibraryPackage(pkg);
16980
16981            // No static shared libs on external storage
16982            if (onExternal) {
16983                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16984                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16985                        "Packages declaring static-shared libs cannot be updated");
16986                return;
16987            }
16988        }
16989
16990        // If we are installing a clustered package add results for the children
16991        if (pkg.childPackages != null) {
16992            synchronized (mPackages) {
16993                final int childCount = pkg.childPackages.size();
16994                for (int i = 0; i < childCount; i++) {
16995                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16996                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16997                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16998                    childRes.pkg = childPkg;
16999                    childRes.name = childPkg.packageName;
17000                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17001                    if (childPs != null) {
17002                        childRes.origUsers = childPs.queryInstalledUsers(
17003                                sUserManager.getUserIds(), true);
17004                    }
17005                    if ((mPackages.containsKey(childPkg.packageName))) {
17006                        childRes.removedInfo = new PackageRemovedInfo(this);
17007                        childRes.removedInfo.removedPackage = childPkg.packageName;
17008                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17009                    }
17010                    if (res.addedChildPackages == null) {
17011                        res.addedChildPackages = new ArrayMap<>();
17012                    }
17013                    res.addedChildPackages.put(childPkg.packageName, childRes);
17014                }
17015            }
17016        }
17017
17018        // If package doesn't declare API override, mark that we have an install
17019        // time CPU ABI override.
17020        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17021            pkg.cpuAbiOverride = args.abiOverride;
17022        }
17023
17024        String pkgName = res.name = pkg.packageName;
17025        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17026            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17027                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17028                return;
17029            }
17030        }
17031
17032        try {
17033            // either use what we've been given or parse directly from the APK
17034            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17035                pkg.setSigningDetails(args.signingDetails);
17036            } else {
17037                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17038            }
17039        } catch (PackageParserException e) {
17040            res.setError("Failed collect during installPackageLI", e);
17041            return;
17042        }
17043
17044        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17045                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17046            Slog.w(TAG, "Instant app package " + pkg.packageName
17047                    + " is not signed with at least APK Signature Scheme v2");
17048            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17049                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17050            return;
17051        }
17052
17053        // Get rid of all references to package scan path via parser.
17054        pp = null;
17055        String oldCodePath = null;
17056        boolean systemApp = false;
17057        synchronized (mPackages) {
17058            // Check if installing already existing package
17059            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17060                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17061                if (pkg.mOriginalPackages != null
17062                        && pkg.mOriginalPackages.contains(oldName)
17063                        && mPackages.containsKey(oldName)) {
17064                    // This package is derived from an original package,
17065                    // and this device has been updating from that original
17066                    // name.  We must continue using the original name, so
17067                    // rename the new package here.
17068                    pkg.setPackageName(oldName);
17069                    pkgName = pkg.packageName;
17070                    replace = true;
17071                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17072                            + oldName + " pkgName=" + pkgName);
17073                } else if (mPackages.containsKey(pkgName)) {
17074                    // This package, under its official name, already exists
17075                    // on the device; we should replace it.
17076                    replace = true;
17077                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17078                }
17079
17080                // Child packages are installed through the parent package
17081                if (pkg.parentPackage != null) {
17082                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17083                            "Package " + pkg.packageName + " is child of package "
17084                                    + pkg.parentPackage.parentPackage + ". Child packages "
17085                                    + "can be updated only through the parent package.");
17086                    return;
17087                }
17088
17089                if (replace) {
17090                    // Prevent apps opting out from runtime permissions
17091                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17092                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17093                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17094                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17095                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17096                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17097                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17098                                        + " doesn't support runtime permissions but the old"
17099                                        + " target SDK " + oldTargetSdk + " does.");
17100                        return;
17101                    }
17102                    // Prevent persistent apps from being updated
17103                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17104                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17105                                "Package " + oldPackage.packageName + " is a persistent app. "
17106                                        + "Persistent apps are not updateable.");
17107                        return;
17108                    }
17109                    // Prevent apps from downgrading their targetSandbox.
17110                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17111                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17112                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17113                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17114                                "Package " + pkg.packageName + " new target sandbox "
17115                                + newTargetSandbox + " is incompatible with the previous value of"
17116                                + oldTargetSandbox + ".");
17117                        return;
17118                    }
17119
17120                    // Prevent installing of child packages
17121                    if (oldPackage.parentPackage != null) {
17122                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17123                                "Package " + pkg.packageName + " is child of package "
17124                                        + oldPackage.parentPackage + ". Child packages "
17125                                        + "can be updated only through the parent package.");
17126                        return;
17127                    }
17128                }
17129            }
17130
17131            PackageSetting ps = mSettings.mPackages.get(pkgName);
17132            if (ps != null) {
17133                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17134
17135                // Static shared libs have same package with different versions where
17136                // we internally use a synthetic package name to allow multiple versions
17137                // of the same package, therefore we need to compare signatures against
17138                // the package setting for the latest library version.
17139                PackageSetting signatureCheckPs = ps;
17140                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17141                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17142                    if (libraryEntry != null) {
17143                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17144                    }
17145                }
17146
17147                // Quick sanity check that we're signed correctly if updating;
17148                // we'll check this again later when scanning, but we want to
17149                // bail early here before tripping over redefined permissions.
17150                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17151                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17152                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17153                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17154                                + pkg.packageName + " upgrade keys do not match the "
17155                                + "previously installed version");
17156                        return;
17157                    }
17158                } else {
17159                    try {
17160                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17161                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17162                        // We don't care about disabledPkgSetting on install for now.
17163                        final boolean compatMatch = verifySignatures(
17164                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17165                                compareRecover);
17166                        // The new KeySets will be re-added later in the scanning process.
17167                        if (compatMatch) {
17168                            synchronized (mPackages) {
17169                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17170                            }
17171                        }
17172                    } catch (PackageManagerException e) {
17173                        res.setError(e.error, e.getMessage());
17174                        return;
17175                    }
17176                }
17177
17178                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17179                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17180                    systemApp = (ps.pkg.applicationInfo.flags &
17181                            ApplicationInfo.FLAG_SYSTEM) != 0;
17182                }
17183                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17184            }
17185
17186            int N = pkg.permissions.size();
17187            for (int i = N-1; i >= 0; i--) {
17188                final PackageParser.Permission perm = pkg.permissions.get(i);
17189                final BasePermission bp =
17190                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17191
17192                // Don't allow anyone but the system to define ephemeral permissions.
17193                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17194                        && !systemApp) {
17195                    Slog.w(TAG, "Non-System package " + pkg.packageName
17196                            + " attempting to delcare ephemeral permission "
17197                            + perm.info.name + "; Removing ephemeral.");
17198                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17199                }
17200
17201                // Check whether the newly-scanned package wants to define an already-defined perm
17202                if (bp != null) {
17203                    // If the defining package is signed with our cert, it's okay.  This
17204                    // also includes the "updating the same package" case, of course.
17205                    // "updating same package" could also involve key-rotation.
17206                    final boolean sigsOk;
17207                    final String sourcePackageName = bp.getSourcePackageName();
17208                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17209                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17210                    if (sourcePackageName.equals(pkg.packageName)
17211                            && (ksms.shouldCheckUpgradeKeySetLocked(
17212                                    sourcePackageSetting, scanFlags))) {
17213                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17214                    } else {
17215
17216                        // in the event of signing certificate rotation, we need to see if the
17217                        // package's certificate has rotated from the current one, or if it is an
17218                        // older certificate with which the current is ok with sharing permissions
17219                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17220                                        pkg.mSigningDetails,
17221                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17222                            sigsOk = true;
17223                        } else if (pkg.mSigningDetails.checkCapability(
17224                                        sourcePackageSetting.signatures.mSigningDetails,
17225                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17226
17227                            // the scanned package checks out, has signing certificate rotation
17228                            // history, and is newer; bring it over
17229                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17230                            sigsOk = true;
17231                        } else {
17232                            sigsOk = false;
17233                        }
17234                    }
17235                    if (!sigsOk) {
17236                        // If the owning package is the system itself, we log but allow
17237                        // install to proceed; we fail the install on all other permission
17238                        // redefinitions.
17239                        if (!sourcePackageName.equals("android")) {
17240                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17241                                    + pkg.packageName + " attempting to redeclare permission "
17242                                    + perm.info.name + " already owned by " + sourcePackageName);
17243                            res.origPermission = perm.info.name;
17244                            res.origPackage = sourcePackageName;
17245                            return;
17246                        } else {
17247                            Slog.w(TAG, "Package " + pkg.packageName
17248                                    + " attempting to redeclare system permission "
17249                                    + perm.info.name + "; ignoring new declaration");
17250                            pkg.permissions.remove(i);
17251                        }
17252                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17253                        // Prevent apps to change protection level to dangerous from any other
17254                        // type as this would allow a privilege escalation where an app adds a
17255                        // normal/signature permission in other app's group and later redefines
17256                        // it as dangerous leading to the group auto-grant.
17257                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17258                                == PermissionInfo.PROTECTION_DANGEROUS) {
17259                            if (bp != null && !bp.isRuntime()) {
17260                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17261                                        + "non-runtime permission " + perm.info.name
17262                                        + " to runtime; keeping old protection level");
17263                                perm.info.protectionLevel = bp.getProtectionLevel();
17264                            }
17265                        }
17266                    }
17267                }
17268            }
17269        }
17270
17271        if (systemApp) {
17272            if (onExternal) {
17273                // Abort update; system app can't be replaced with app on sdcard
17274                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17275                        "Cannot install updates to system apps on sdcard");
17276                return;
17277            } else if (instantApp) {
17278                // Abort update; system app can't be replaced with an instant app
17279                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17280                        "Cannot update a system app with an instant app");
17281                return;
17282            }
17283        }
17284
17285        if (args.move != null) {
17286            // We did an in-place move, so dex is ready to roll
17287            scanFlags |= SCAN_NO_DEX;
17288            scanFlags |= SCAN_MOVE;
17289
17290            synchronized (mPackages) {
17291                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17292                if (ps == null) {
17293                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17294                            "Missing settings for moved package " + pkgName);
17295                }
17296
17297                // We moved the entire application as-is, so bring over the
17298                // previously derived ABI information.
17299                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17300                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17301            }
17302
17303        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17304            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17305            scanFlags |= SCAN_NO_DEX;
17306
17307            try {
17308                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17309                    args.abiOverride : pkg.cpuAbiOverride);
17310                final boolean extractNativeLibs = !pkg.isLibrary();
17311                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17312            } catch (PackageManagerException pme) {
17313                Slog.e(TAG, "Error deriving application ABI", pme);
17314                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17315                return;
17316            }
17317
17318            // Shared libraries for the package need to be updated.
17319            synchronized (mPackages) {
17320                try {
17321                    updateSharedLibrariesLPr(pkg, null);
17322                } catch (PackageManagerException e) {
17323                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17324                }
17325            }
17326        }
17327
17328        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17329            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17330            return;
17331        }
17332
17333        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17334            String apkPath = null;
17335            synchronized (mPackages) {
17336                // Note that if the attacker managed to skip verify setup, for example by tampering
17337                // with the package settings, upon reboot we will do full apk verification when
17338                // verity is not detected.
17339                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17340                if (ps != null && ps.isPrivileged()) {
17341                    apkPath = pkg.baseCodePath;
17342                }
17343            }
17344
17345            if (apkPath != null) {
17346                final VerityUtils.SetupResult result =
17347                        VerityUtils.generateApkVeritySetupData(apkPath);
17348                if (result.isOk()) {
17349                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17350                    FileDescriptor fd = result.getUnownedFileDescriptor();
17351                    try {
17352                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17353                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17354                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17355                    } catch (InstallerException | IOException | DigestException |
17356                             NoSuchAlgorithmException e) {
17357                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17358                                "Failed to set up verity: " + e);
17359                        return;
17360                    } finally {
17361                        IoUtils.closeQuietly(fd);
17362                    }
17363                } else if (result.isFailed()) {
17364                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17365                    return;
17366                } else {
17367                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17368                    // reboot.
17369                }
17370            }
17371        }
17372
17373        if (!instantApp) {
17374            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17375        } else {
17376            if (DEBUG_DOMAIN_VERIFICATION) {
17377                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17378            }
17379        }
17380
17381        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17382                "installPackageLI")) {
17383            if (replace) {
17384                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17385                    // Static libs have a synthetic package name containing the version
17386                    // and cannot be updated as an update would get a new package name,
17387                    // unless this is the exact same version code which is useful for
17388                    // development.
17389                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17390                    if (existingPkg != null &&
17391                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17392                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17393                                + "static-shared libs cannot be updated");
17394                        return;
17395                    }
17396                }
17397                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17398                        installerPackageName, res, args.installReason);
17399            } else {
17400                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17401                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17402            }
17403        }
17404
17405        // Prepare the application profiles for the new code paths.
17406        // This needs to be done before invoking dexopt so that any install-time profile
17407        // can be used for optimizations.
17408        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17409
17410        // Check whether we need to dexopt the app.
17411        //
17412        // NOTE: it is IMPORTANT to call dexopt:
17413        //   - after doRename which will sync the package data from PackageParser.Package and its
17414        //     corresponding ApplicationInfo.
17415        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17416        //     uid of the application (pkg.applicationInfo.uid).
17417        //     This update happens in place!
17418        //
17419        // We only need to dexopt if the package meets ALL of the following conditions:
17420        //   1) it is not forward locked.
17421        //   2) it is not on on an external ASEC container.
17422        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17423        //   4) it is not debuggable.
17424        //
17425        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17426        // complete, so we skip this step during installation. Instead, we'll take extra time
17427        // the first time the instant app starts. It's preferred to do it this way to provide
17428        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17429        // middle of running an instant app. The default behaviour can be overridden
17430        // via gservices.
17431        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17432                && !forwardLocked
17433                && !pkg.applicationInfo.isExternalAsec()
17434                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17435                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17436                && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17437
17438        if (performDexopt) {
17439            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17440            // Do not run PackageDexOptimizer through the local performDexOpt
17441            // method because `pkg` may not be in `mPackages` yet.
17442            //
17443            // Also, don't fail application installs if the dexopt step fails.
17444            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17445                    REASON_INSTALL,
17446                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17447                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17448            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17449                    null /* instructionSets */,
17450                    getOrCreateCompilerPackageStats(pkg),
17451                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17452                    dexoptOptions);
17453            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17454        }
17455
17456        // Notify BackgroundDexOptService that the package has been changed.
17457        // If this is an update of a package which used to fail to compile,
17458        // BackgroundDexOptService will remove it from its blacklist.
17459        // TODO: Layering violation
17460        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17461
17462        synchronized (mPackages) {
17463            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17464            if (ps != null) {
17465                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17466                ps.setUpdateAvailable(false /*updateAvailable*/);
17467            }
17468
17469            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17470            for (int i = 0; i < childCount; i++) {
17471                PackageParser.Package childPkg = pkg.childPackages.get(i);
17472                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17473                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17474                if (childPs != null) {
17475                    childRes.newUsers = childPs.queryInstalledUsers(
17476                            sUserManager.getUserIds(), true);
17477                }
17478            }
17479
17480            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17481                updateSequenceNumberLP(ps, res.newUsers);
17482                updateInstantAppInstallerLocked(pkgName);
17483            }
17484        }
17485    }
17486
17487    private void startIntentFilterVerifications(int userId, boolean replacing,
17488            PackageParser.Package pkg) {
17489        if (mIntentFilterVerifierComponent == null) {
17490            Slog.w(TAG, "No IntentFilter verification will not be done as "
17491                    + "there is no IntentFilterVerifier available!");
17492            return;
17493        }
17494
17495        final int verifierUid = getPackageUid(
17496                mIntentFilterVerifierComponent.getPackageName(),
17497                MATCH_DEBUG_TRIAGED_MISSING,
17498                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17499
17500        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17501        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17502        mHandler.sendMessage(msg);
17503
17504        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17505        for (int i = 0; i < childCount; i++) {
17506            PackageParser.Package childPkg = pkg.childPackages.get(i);
17507            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17508            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17509            mHandler.sendMessage(msg);
17510        }
17511    }
17512
17513    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17514            PackageParser.Package pkg) {
17515        int size = pkg.activities.size();
17516        if (size == 0) {
17517            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17518                    "No activity, so no need to verify any IntentFilter!");
17519            return;
17520        }
17521
17522        final boolean hasDomainURLs = hasDomainURLs(pkg);
17523        if (!hasDomainURLs) {
17524            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17525                    "No domain URLs, so no need to verify any IntentFilter!");
17526            return;
17527        }
17528
17529        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17530                + " if any IntentFilter from the " + size
17531                + " Activities needs verification ...");
17532
17533        int count = 0;
17534        final String packageName = pkg.packageName;
17535
17536        synchronized (mPackages) {
17537            // If this is a new install and we see that we've already run verification for this
17538            // package, we have nothing to do: it means the state was restored from backup.
17539            if (!replacing) {
17540                IntentFilterVerificationInfo ivi =
17541                        mSettings.getIntentFilterVerificationLPr(packageName);
17542                if (ivi != null) {
17543                    if (DEBUG_DOMAIN_VERIFICATION) {
17544                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17545                                + ivi.getStatusString());
17546                    }
17547                    return;
17548                }
17549            }
17550
17551            // If any filters need to be verified, then all need to be.
17552            boolean needToVerify = false;
17553            for (PackageParser.Activity a : pkg.activities) {
17554                for (ActivityIntentInfo filter : a.intents) {
17555                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17556                        if (DEBUG_DOMAIN_VERIFICATION) {
17557                            Slog.d(TAG,
17558                                    "Intent filter needs verification, so processing all filters");
17559                        }
17560                        needToVerify = true;
17561                        break;
17562                    }
17563                }
17564            }
17565
17566            if (needToVerify) {
17567                final int verificationId = mIntentFilterVerificationToken++;
17568                for (PackageParser.Activity a : pkg.activities) {
17569                    for (ActivityIntentInfo filter : a.intents) {
17570                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17571                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17572                                    "Verification needed for IntentFilter:" + filter.toString());
17573                            mIntentFilterVerifier.addOneIntentFilterVerification(
17574                                    verifierUid, userId, verificationId, filter, packageName);
17575                            count++;
17576                        }
17577                    }
17578                }
17579            }
17580        }
17581
17582        if (count > 0) {
17583            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17584                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17585                    +  " for userId:" + userId);
17586            mIntentFilterVerifier.startVerifications(userId);
17587        } else {
17588            if (DEBUG_DOMAIN_VERIFICATION) {
17589                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17590            }
17591        }
17592    }
17593
17594    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17595        final ComponentName cn  = filter.activity.getComponentName();
17596        final String packageName = cn.getPackageName();
17597
17598        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17599                packageName);
17600        if (ivi == null) {
17601            return true;
17602        }
17603        int status = ivi.getStatus();
17604        switch (status) {
17605            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17606            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17607                return true;
17608
17609            default:
17610                // Nothing to do
17611                return false;
17612        }
17613    }
17614
17615    private static boolean isMultiArch(ApplicationInfo info) {
17616        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17617    }
17618
17619    private static boolean isExternal(PackageParser.Package pkg) {
17620        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17621    }
17622
17623    private static boolean isExternal(PackageSetting ps) {
17624        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17625    }
17626
17627    private static boolean isSystemApp(PackageParser.Package pkg) {
17628        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17629    }
17630
17631    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17632        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17633    }
17634
17635    private static boolean isOemApp(PackageParser.Package pkg) {
17636        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17637    }
17638
17639    private static boolean isVendorApp(PackageParser.Package pkg) {
17640        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17641    }
17642
17643    private static boolean isProductApp(PackageParser.Package pkg) {
17644        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17645    }
17646
17647    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17648        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17649    }
17650
17651    private static boolean isSystemApp(PackageSetting ps) {
17652        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17653    }
17654
17655    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17656        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17657    }
17658
17659    private int packageFlagsToInstallFlags(PackageSetting ps) {
17660        int installFlags = 0;
17661        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17662            // This existing package was an external ASEC install when we have
17663            // the external flag without a UUID
17664            installFlags |= PackageManager.INSTALL_EXTERNAL;
17665        }
17666        if (ps.isForwardLocked()) {
17667            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17668        }
17669        return installFlags;
17670    }
17671
17672    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17673        if (isExternal(pkg)) {
17674            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17675                return mSettings.getExternalVersion();
17676            } else {
17677                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17678            }
17679        } else {
17680            return mSettings.getInternalVersion();
17681        }
17682    }
17683
17684    private void deleteTempPackageFiles() {
17685        final FilenameFilter filter = new FilenameFilter() {
17686            public boolean accept(File dir, String name) {
17687                return name.startsWith("vmdl") && name.endsWith(".tmp");
17688            }
17689        };
17690        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17691            file.delete();
17692        }
17693    }
17694
17695    @Override
17696    public void deletePackageAsUser(String packageName, int versionCode,
17697            IPackageDeleteObserver observer, int userId, int flags) {
17698        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17699                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17700    }
17701
17702    @Override
17703    public void deletePackageVersioned(VersionedPackage versionedPackage,
17704            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17705        final int callingUid = Binder.getCallingUid();
17706        mContext.enforceCallingOrSelfPermission(
17707                android.Manifest.permission.DELETE_PACKAGES, null);
17708        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17709        Preconditions.checkNotNull(versionedPackage);
17710        Preconditions.checkNotNull(observer);
17711        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17712                PackageManager.VERSION_CODE_HIGHEST,
17713                Long.MAX_VALUE, "versionCode must be >= -1");
17714
17715        final String packageName = versionedPackage.getPackageName();
17716        final long versionCode = versionedPackage.getLongVersionCode();
17717        final String internalPackageName;
17718        synchronized (mPackages) {
17719            // Normalize package name to handle renamed packages and static libs
17720            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17721        }
17722
17723        final int uid = Binder.getCallingUid();
17724        if (!isOrphaned(internalPackageName)
17725                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17726            try {
17727                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17728                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17729                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17730                observer.onUserActionRequired(intent);
17731            } catch (RemoteException re) {
17732            }
17733            return;
17734        }
17735        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17736        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17737        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17738            mContext.enforceCallingOrSelfPermission(
17739                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17740                    "deletePackage for user " + userId);
17741        }
17742
17743        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17744            try {
17745                observer.onPackageDeleted(packageName,
17746                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17747            } catch (RemoteException re) {
17748            }
17749            return;
17750        }
17751
17752        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17753            try {
17754                observer.onPackageDeleted(packageName,
17755                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17756            } catch (RemoteException re) {
17757            }
17758            return;
17759        }
17760
17761        if (DEBUG_REMOVE) {
17762            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17763                    + " deleteAllUsers: " + deleteAllUsers + " version="
17764                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17765                    ? "VERSION_CODE_HIGHEST" : versionCode));
17766        }
17767        // Queue up an async operation since the package deletion may take a little while.
17768        mHandler.post(new Runnable() {
17769            public void run() {
17770                mHandler.removeCallbacks(this);
17771                int returnCode;
17772                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17773                boolean doDeletePackage = true;
17774                if (ps != null) {
17775                    final boolean targetIsInstantApp =
17776                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17777                    doDeletePackage = !targetIsInstantApp
17778                            || canViewInstantApps;
17779                }
17780                if (doDeletePackage) {
17781                    if (!deleteAllUsers) {
17782                        returnCode = deletePackageX(internalPackageName, versionCode,
17783                                userId, deleteFlags);
17784                    } else {
17785                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17786                                internalPackageName, users);
17787                        // If nobody is blocking uninstall, proceed with delete for all users
17788                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17789                            returnCode = deletePackageX(internalPackageName, versionCode,
17790                                    userId, deleteFlags);
17791                        } else {
17792                            // Otherwise uninstall individually for users with blockUninstalls=false
17793                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17794                            for (int userId : users) {
17795                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17796                                    returnCode = deletePackageX(internalPackageName, versionCode,
17797                                            userId, userFlags);
17798                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17799                                        Slog.w(TAG, "Package delete failed for user " + userId
17800                                                + ", returnCode " + returnCode);
17801                                    }
17802                                }
17803                            }
17804                            // The app has only been marked uninstalled for certain users.
17805                            // We still need to report that delete was blocked
17806                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17807                        }
17808                    }
17809                } else {
17810                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17811                }
17812                try {
17813                    observer.onPackageDeleted(packageName, returnCode, null);
17814                } catch (RemoteException e) {
17815                    Log.i(TAG, "Observer no longer exists.");
17816                } //end catch
17817            } //end run
17818        });
17819    }
17820
17821    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17822        if (pkg.staticSharedLibName != null) {
17823            return pkg.manifestPackageName;
17824        }
17825        return pkg.packageName;
17826    }
17827
17828    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17829        // Handle renamed packages
17830        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17831        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17832
17833        // Is this a static library?
17834        LongSparseArray<SharedLibraryEntry> versionedLib =
17835                mStaticLibsByDeclaringPackage.get(packageName);
17836        if (versionedLib == null || versionedLib.size() <= 0) {
17837            return packageName;
17838        }
17839
17840        // Figure out which lib versions the caller can see
17841        LongSparseLongArray versionsCallerCanSee = null;
17842        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17843        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17844                && callingAppId != Process.ROOT_UID) {
17845            versionsCallerCanSee = new LongSparseLongArray();
17846            String libName = versionedLib.valueAt(0).info.getName();
17847            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17848            if (uidPackages != null) {
17849                for (String uidPackage : uidPackages) {
17850                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17851                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17852                    if (libIdx >= 0) {
17853                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17854                        versionsCallerCanSee.append(libVersion, libVersion);
17855                    }
17856                }
17857            }
17858        }
17859
17860        // Caller can see nothing - done
17861        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17862            return packageName;
17863        }
17864
17865        // Find the version the caller can see and the app version code
17866        SharedLibraryEntry highestVersion = null;
17867        final int versionCount = versionedLib.size();
17868        for (int i = 0; i < versionCount; i++) {
17869            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17870            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17871                    libEntry.info.getLongVersion()) < 0) {
17872                continue;
17873            }
17874            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17875            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17876                if (libVersionCode == versionCode) {
17877                    return libEntry.apk;
17878                }
17879            } else if (highestVersion == null) {
17880                highestVersion = libEntry;
17881            } else if (libVersionCode  > highestVersion.info
17882                    .getDeclaringPackage().getLongVersionCode()) {
17883                highestVersion = libEntry;
17884            }
17885        }
17886
17887        if (highestVersion != null) {
17888            return highestVersion.apk;
17889        }
17890
17891        return packageName;
17892    }
17893
17894    boolean isCallerVerifier(int callingUid) {
17895        final int callingUserId = UserHandle.getUserId(callingUid);
17896        return mRequiredVerifierPackage != null &&
17897                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17898    }
17899
17900    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17901        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17902              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17903            return true;
17904        }
17905        final int callingUserId = UserHandle.getUserId(callingUid);
17906        // If the caller installed the pkgName, then allow it to silently uninstall.
17907        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17908            return true;
17909        }
17910
17911        // Allow package verifier to silently uninstall.
17912        if (mRequiredVerifierPackage != null &&
17913                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17914            return true;
17915        }
17916
17917        // Allow package uninstaller to silently uninstall.
17918        if (mRequiredUninstallerPackage != null &&
17919                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17920            return true;
17921        }
17922
17923        // Allow storage manager to silently uninstall.
17924        if (mStorageManagerPackage != null &&
17925                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17926            return true;
17927        }
17928
17929        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17930        // uninstall for device owner provisioning.
17931        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17932                == PERMISSION_GRANTED) {
17933            return true;
17934        }
17935
17936        return false;
17937    }
17938
17939    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17940        int[] result = EMPTY_INT_ARRAY;
17941        for (int userId : userIds) {
17942            if (getBlockUninstallForUser(packageName, userId)) {
17943                result = ArrayUtils.appendInt(result, userId);
17944            }
17945        }
17946        return result;
17947    }
17948
17949    @Override
17950    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17951        final int callingUid = Binder.getCallingUid();
17952        if (getInstantAppPackageName(callingUid) != null
17953                && !isCallerSameApp(packageName, callingUid)) {
17954            return false;
17955        }
17956        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17957    }
17958
17959    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17960        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17961                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17962        try {
17963            if (dpm != null) {
17964                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17965                        /* callingUserOnly =*/ false);
17966                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17967                        : deviceOwnerComponentName.getPackageName();
17968                // Does the package contains the device owner?
17969                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17970                // this check is probably not needed, since DO should be registered as a device
17971                // admin on some user too. (Original bug for this: b/17657954)
17972                if (packageName.equals(deviceOwnerPackageName)) {
17973                    return true;
17974                }
17975                // Does it contain a device admin for any user?
17976                int[] users;
17977                if (userId == UserHandle.USER_ALL) {
17978                    users = sUserManager.getUserIds();
17979                } else {
17980                    users = new int[]{userId};
17981                }
17982                for (int i = 0; i < users.length; ++i) {
17983                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17984                        return true;
17985                    }
17986                }
17987            }
17988        } catch (RemoteException e) {
17989        }
17990        return false;
17991    }
17992
17993    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17994        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17995    }
17996
17997    /**
17998     *  This method is an internal method that could be get invoked either
17999     *  to delete an installed package or to clean up a failed installation.
18000     *  After deleting an installed package, a broadcast is sent to notify any
18001     *  listeners that the package has been removed. For cleaning up a failed
18002     *  installation, the broadcast is not necessary since the package's
18003     *  installation wouldn't have sent the initial broadcast either
18004     *  The key steps in deleting a package are
18005     *  deleting the package information in internal structures like mPackages,
18006     *  deleting the packages base directories through installd
18007     *  updating mSettings to reflect current status
18008     *  persisting settings for later use
18009     *  sending a broadcast if necessary
18010     */
18011    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18012        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18013        final boolean res;
18014
18015        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18016                ? UserHandle.USER_ALL : userId;
18017
18018        if (isPackageDeviceAdmin(packageName, removeUser)) {
18019            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18020            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18021        }
18022
18023        PackageSetting uninstalledPs = null;
18024        PackageParser.Package pkg = null;
18025
18026        // for the uninstall-updates case and restricted profiles, remember the per-
18027        // user handle installed state
18028        int[] allUsers;
18029        synchronized (mPackages) {
18030            uninstalledPs = mSettings.mPackages.get(packageName);
18031            if (uninstalledPs == null) {
18032                Slog.w(TAG, "Not removing non-existent package " + packageName);
18033                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18034            }
18035
18036            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18037                    && uninstalledPs.versionCode != versionCode) {
18038                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18039                        + uninstalledPs.versionCode + " != " + versionCode);
18040                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18041            }
18042
18043            // Static shared libs can be declared by any package, so let us not
18044            // allow removing a package if it provides a lib others depend on.
18045            pkg = mPackages.get(packageName);
18046
18047            allUsers = sUserManager.getUserIds();
18048
18049            if (pkg != null && pkg.staticSharedLibName != null) {
18050                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18051                        pkg.staticSharedLibVersion);
18052                if (libEntry != null) {
18053                    for (int currUserId : allUsers) {
18054                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18055                            continue;
18056                        }
18057                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18058                                libEntry.info, 0, currUserId);
18059                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18060                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18061                                    + " hosting lib " + libEntry.info.getName() + " version "
18062                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18063                                    + " for user " + currUserId);
18064                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18065                        }
18066                    }
18067                }
18068            }
18069
18070            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18071        }
18072
18073        final int freezeUser;
18074        if (isUpdatedSystemApp(uninstalledPs)
18075                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18076            // We're downgrading a system app, which will apply to all users, so
18077            // freeze them all during the downgrade
18078            freezeUser = UserHandle.USER_ALL;
18079        } else {
18080            freezeUser = removeUser;
18081        }
18082
18083        synchronized (mInstallLock) {
18084            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18085            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18086                    deleteFlags, "deletePackageX")) {
18087                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18088                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18089            }
18090            synchronized (mPackages) {
18091                if (res) {
18092                    if (pkg != null) {
18093                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18094                    }
18095                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18096                    updateInstantAppInstallerLocked(packageName);
18097                }
18098            }
18099        }
18100
18101        if (res) {
18102            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18103            info.sendPackageRemovedBroadcasts(killApp);
18104            info.sendSystemPackageUpdatedBroadcasts();
18105            info.sendSystemPackageAppearedBroadcasts();
18106        }
18107        // Force a gc here.
18108        Runtime.getRuntime().gc();
18109        // Delete the resources here after sending the broadcast to let
18110        // other processes clean up before deleting resources.
18111        if (info.args != null) {
18112            synchronized (mInstallLock) {
18113                info.args.doPostDeleteLI(true);
18114            }
18115        }
18116
18117        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18118    }
18119
18120    static class PackageRemovedInfo {
18121        final PackageSender packageSender;
18122        String removedPackage;
18123        String installerPackageName;
18124        int uid = -1;
18125        int removedAppId = -1;
18126        int[] origUsers;
18127        int[] removedUsers = null;
18128        int[] broadcastUsers = null;
18129        int[] instantUserIds = null;
18130        SparseArray<Integer> installReasons;
18131        boolean isRemovedPackageSystemUpdate = false;
18132        boolean isUpdate;
18133        boolean dataRemoved;
18134        boolean removedForAllUsers;
18135        boolean isStaticSharedLib;
18136        // Clean up resources deleted packages.
18137        InstallArgs args = null;
18138        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18139        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18140
18141        PackageRemovedInfo(PackageSender packageSender) {
18142            this.packageSender = packageSender;
18143        }
18144
18145        void sendPackageRemovedBroadcasts(boolean killApp) {
18146            sendPackageRemovedBroadcastInternal(killApp);
18147            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18148            for (int i = 0; i < childCount; i++) {
18149                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18150                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18151            }
18152        }
18153
18154        void sendSystemPackageUpdatedBroadcasts() {
18155            if (isRemovedPackageSystemUpdate) {
18156                sendSystemPackageUpdatedBroadcastsInternal();
18157                final int childCount = (removedChildPackages != null)
18158                        ? removedChildPackages.size() : 0;
18159                for (int i = 0; i < childCount; i++) {
18160                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18161                    if (childInfo.isRemovedPackageSystemUpdate) {
18162                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18163                    }
18164                }
18165            }
18166        }
18167
18168        void sendSystemPackageAppearedBroadcasts() {
18169            final int packageCount = (appearedChildPackages != null)
18170                    ? appearedChildPackages.size() : 0;
18171            for (int i = 0; i < packageCount; i++) {
18172                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18173                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18174                    true /*sendBootCompleted*/, false /*startReceiver*/,
18175                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18176            }
18177        }
18178
18179        private void sendSystemPackageUpdatedBroadcastsInternal() {
18180            Bundle extras = new Bundle(2);
18181            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18182            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18183            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18184                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18185            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18186                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18187            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18188                null, null, 0, removedPackage, null, null, null);
18189            if (installerPackageName != null) {
18190                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18191                        removedPackage, extras, 0 /*flags*/,
18192                        installerPackageName, null, null, null);
18193                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18194                        removedPackage, extras, 0 /*flags*/,
18195                        installerPackageName, null, null, null);
18196            }
18197        }
18198
18199        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18200            // Don't send static shared library removal broadcasts as these
18201            // libs are visible only the the apps that depend on them an one
18202            // cannot remove the library if it has a dependency.
18203            if (isStaticSharedLib) {
18204                return;
18205            }
18206            Bundle extras = new Bundle(2);
18207            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18208            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18209            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18210            if (isUpdate || isRemovedPackageSystemUpdate) {
18211                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18212            }
18213            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18214            if (removedPackage != null) {
18215                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18216                    removedPackage, extras, 0, null /*targetPackage*/, null,
18217                    broadcastUsers, instantUserIds);
18218                if (installerPackageName != null) {
18219                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18220                            removedPackage, extras, 0 /*flags*/,
18221                            installerPackageName, null, broadcastUsers, instantUserIds);
18222                }
18223                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18224                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18225                        removedPackage, extras,
18226                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18227                        null, null, broadcastUsers, instantUserIds);
18228                    packageSender.notifyPackageRemoved(removedPackage);
18229                }
18230            }
18231            if (removedAppId >= 0) {
18232                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18233                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18234                    null, null, broadcastUsers, instantUserIds);
18235            }
18236        }
18237
18238        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18239            removedUsers = userIds;
18240            if (removedUsers == null) {
18241                broadcastUsers = null;
18242                return;
18243            }
18244
18245            broadcastUsers = EMPTY_INT_ARRAY;
18246            instantUserIds = EMPTY_INT_ARRAY;
18247            for (int i = userIds.length - 1; i >= 0; --i) {
18248                final int userId = userIds[i];
18249                if (deletedPackageSetting.getInstantApp(userId)) {
18250                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18251                } else {
18252                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18253                }
18254            }
18255        }
18256    }
18257
18258    /*
18259     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18260     * flag is not set, the data directory is removed as well.
18261     * make sure this flag is set for partially installed apps. If not its meaningless to
18262     * delete a partially installed application.
18263     */
18264    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18265            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18266        String packageName = ps.name;
18267        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18268        // Retrieve object to delete permissions for shared user later on
18269        final PackageParser.Package deletedPkg;
18270        final PackageSetting deletedPs;
18271        // reader
18272        synchronized (mPackages) {
18273            deletedPkg = mPackages.get(packageName);
18274            deletedPs = mSettings.mPackages.get(packageName);
18275            if (outInfo != null) {
18276                outInfo.removedPackage = packageName;
18277                outInfo.installerPackageName = ps.installerPackageName;
18278                outInfo.isStaticSharedLib = deletedPkg != null
18279                        && deletedPkg.staticSharedLibName != null;
18280                outInfo.populateUsers(deletedPs == null ? null
18281                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18282            }
18283        }
18284
18285        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18286
18287        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18288            final PackageParser.Package resolvedPkg;
18289            if (deletedPkg != null) {
18290                resolvedPkg = deletedPkg;
18291            } else {
18292                // We don't have a parsed package when it lives on an ejected
18293                // adopted storage device, so fake something together
18294                resolvedPkg = new PackageParser.Package(ps.name);
18295                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18296            }
18297            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18298                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18299            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18300            if (outInfo != null) {
18301                outInfo.dataRemoved = true;
18302            }
18303            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18304        }
18305
18306        int removedAppId = -1;
18307
18308        // writer
18309        synchronized (mPackages) {
18310            boolean installedStateChanged = false;
18311            if (deletedPs != null) {
18312                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18313                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18314                    clearDefaultBrowserIfNeeded(packageName);
18315                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18316                    removedAppId = mSettings.removePackageLPw(packageName);
18317                    if (outInfo != null) {
18318                        outInfo.removedAppId = removedAppId;
18319                    }
18320                    mPermissionManager.updatePermissions(
18321                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18322                    if (deletedPs.sharedUser != null) {
18323                        // Remove permissions associated with package. Since runtime
18324                        // permissions are per user we have to kill the removed package
18325                        // or packages running under the shared user of the removed
18326                        // package if revoking the permissions requested only by the removed
18327                        // package is successful and this causes a change in gids.
18328                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18329                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18330                                    userId);
18331                            if (userIdToKill == UserHandle.USER_ALL
18332                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18333                                // If gids changed for this user, kill all affected packages.
18334                                mHandler.post(new Runnable() {
18335                                    @Override
18336                                    public void run() {
18337                                        // This has to happen with no lock held.
18338                                        killApplication(deletedPs.name, deletedPs.appId,
18339                                                KILL_APP_REASON_GIDS_CHANGED);
18340                                    }
18341                                });
18342                                break;
18343                            }
18344                        }
18345                    }
18346                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18347                }
18348                // make sure to preserve per-user disabled state if this removal was just
18349                // a downgrade of a system app to the factory package
18350                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18351                    if (DEBUG_REMOVE) {
18352                        Slog.d(TAG, "Propagating install state across downgrade");
18353                    }
18354                    for (int userId : allUserHandles) {
18355                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18356                        if (DEBUG_REMOVE) {
18357                            Slog.d(TAG, "    user " + userId + " => " + installed);
18358                        }
18359                        if (installed != ps.getInstalled(userId)) {
18360                            installedStateChanged = true;
18361                        }
18362                        ps.setInstalled(installed, userId);
18363                    }
18364                }
18365            }
18366            // can downgrade to reader
18367            if (writeSettings) {
18368                // Save settings now
18369                mSettings.writeLPr();
18370            }
18371            if (installedStateChanged) {
18372                mSettings.writeKernelMappingLPr(ps);
18373            }
18374        }
18375        if (removedAppId != -1) {
18376            // A user ID was deleted here. Go through all users and remove it
18377            // from KeyStore.
18378            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18379        }
18380    }
18381
18382    static boolean locationIsPrivileged(String path) {
18383        try {
18384            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18385            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18386            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18387            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18388            return path.startsWith(privilegedAppDir.getCanonicalPath())
18389                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18390                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18391                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18392        } catch (IOException e) {
18393            Slog.e(TAG, "Unable to access code path " + path);
18394        }
18395        return false;
18396    }
18397
18398    static boolean locationIsOem(String path) {
18399        try {
18400            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18401        } catch (IOException e) {
18402            Slog.e(TAG, "Unable to access code path " + path);
18403        }
18404        return false;
18405    }
18406
18407    static boolean locationIsVendor(String path) {
18408        try {
18409            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18410                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18411        } catch (IOException e) {
18412            Slog.e(TAG, "Unable to access code path " + path);
18413        }
18414        return false;
18415    }
18416
18417    static boolean locationIsProduct(String path) {
18418        try {
18419            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18420        } catch (IOException e) {
18421            Slog.e(TAG, "Unable to access code path " + path);
18422        }
18423        return false;
18424    }
18425
18426    /*
18427     * Tries to delete system package.
18428     */
18429    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18430            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18431            boolean writeSettings) {
18432        if (deletedPs.parentPackageName != null) {
18433            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18434            return false;
18435        }
18436
18437        final boolean applyUserRestrictions
18438                = (allUserHandles != null) && (outInfo.origUsers != null);
18439        final PackageSetting disabledPs;
18440        // Confirm if the system package has been updated
18441        // An updated system app can be deleted. This will also have to restore
18442        // the system pkg from system partition
18443        // reader
18444        synchronized (mPackages) {
18445            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18446        }
18447
18448        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18449                + " disabledPs=" + disabledPs);
18450
18451        if (disabledPs == null) {
18452            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18453            return false;
18454        } else if (DEBUG_REMOVE) {
18455            Slog.d(TAG, "Deleting system pkg from data partition");
18456        }
18457
18458        if (DEBUG_REMOVE) {
18459            if (applyUserRestrictions) {
18460                Slog.d(TAG, "Remembering install states:");
18461                for (int userId : allUserHandles) {
18462                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18463                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18464                }
18465            }
18466        }
18467
18468        // Delete the updated package
18469        outInfo.isRemovedPackageSystemUpdate = true;
18470        if (outInfo.removedChildPackages != null) {
18471            final int childCount = (deletedPs.childPackageNames != null)
18472                    ? deletedPs.childPackageNames.size() : 0;
18473            for (int i = 0; i < childCount; i++) {
18474                String childPackageName = deletedPs.childPackageNames.get(i);
18475                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18476                        .contains(childPackageName)) {
18477                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18478                            childPackageName);
18479                    if (childInfo != null) {
18480                        childInfo.isRemovedPackageSystemUpdate = true;
18481                    }
18482                }
18483            }
18484        }
18485
18486        if (disabledPs.versionCode < deletedPs.versionCode) {
18487            // Delete data for downgrades
18488            flags &= ~PackageManager.DELETE_KEEP_DATA;
18489        } else {
18490            // Preserve data by setting flag
18491            flags |= PackageManager.DELETE_KEEP_DATA;
18492        }
18493
18494        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18495                outInfo, writeSettings, disabledPs.pkg);
18496        if (!ret) {
18497            return false;
18498        }
18499
18500        // writer
18501        synchronized (mPackages) {
18502            // NOTE: The system package always needs to be enabled; even if it's for
18503            // a compressed stub. If we don't, installing the system package fails
18504            // during scan [scanning checks the disabled packages]. We will reverse
18505            // this later, after we've "installed" the stub.
18506            // Reinstate the old system package
18507            enableSystemPackageLPw(disabledPs.pkg);
18508            // Remove any native libraries from the upgraded package.
18509            removeNativeBinariesLI(deletedPs);
18510        }
18511
18512        // Install the system package
18513        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18514        try {
18515            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18516                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18517        } catch (PackageManagerException e) {
18518            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18519                    + e.getMessage());
18520            return false;
18521        } finally {
18522            if (disabledPs.pkg.isStub) {
18523                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18524            }
18525        }
18526        return true;
18527    }
18528
18529    /**
18530     * Installs a package that's already on the system partition.
18531     */
18532    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18533            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18534            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18535                    throws PackageManagerException {
18536        @ParseFlags int parseFlags =
18537                mDefParseFlags
18538                | PackageParser.PARSE_MUST_BE_APK
18539                | PackageParser.PARSE_IS_SYSTEM_DIR;
18540        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18541        if (isPrivileged || locationIsPrivileged(codePathString)) {
18542            scanFlags |= SCAN_AS_PRIVILEGED;
18543        }
18544        if (locationIsOem(codePathString)) {
18545            scanFlags |= SCAN_AS_OEM;
18546        }
18547        if (locationIsVendor(codePathString)) {
18548            scanFlags |= SCAN_AS_VENDOR;
18549        }
18550        if (locationIsProduct(codePathString)) {
18551            scanFlags |= SCAN_AS_PRODUCT;
18552        }
18553
18554        final File codePath = new File(codePathString);
18555        final PackageParser.Package pkg =
18556                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18557
18558        try {
18559            // update shared libraries for the newly re-installed system package
18560            updateSharedLibrariesLPr(pkg, null);
18561        } catch (PackageManagerException e) {
18562            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18563        }
18564
18565        prepareAppDataAfterInstallLIF(pkg);
18566
18567        // writer
18568        synchronized (mPackages) {
18569            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18570
18571            // Propagate the permissions state as we do not want to drop on the floor
18572            // runtime permissions. The update permissions method below will take
18573            // care of removing obsolete permissions and grant install permissions.
18574            if (origPermissionState != null) {
18575                ps.getPermissionsState().copyFrom(origPermissionState);
18576            }
18577            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18578                    mPermissionCallback);
18579
18580            final boolean applyUserRestrictions
18581                    = (allUserHandles != null) && (origUserHandles != null);
18582            if (applyUserRestrictions) {
18583                boolean installedStateChanged = false;
18584                if (DEBUG_REMOVE) {
18585                    Slog.d(TAG, "Propagating install state across reinstall");
18586                }
18587                for (int userId : allUserHandles) {
18588                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18589                    if (DEBUG_REMOVE) {
18590                        Slog.d(TAG, "    user " + userId + " => " + installed);
18591                    }
18592                    if (installed != ps.getInstalled(userId)) {
18593                        installedStateChanged = true;
18594                    }
18595                    ps.setInstalled(installed, userId);
18596
18597                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18598                }
18599                // Regardless of writeSettings we need to ensure that this restriction
18600                // state propagation is persisted
18601                mSettings.writeAllUsersPackageRestrictionsLPr();
18602                if (installedStateChanged) {
18603                    mSettings.writeKernelMappingLPr(ps);
18604                }
18605            }
18606            // can downgrade to reader here
18607            if (writeSettings) {
18608                mSettings.writeLPr();
18609            }
18610        }
18611        return pkg;
18612    }
18613
18614    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18615            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18616            PackageRemovedInfo outInfo, boolean writeSettings,
18617            PackageParser.Package replacingPackage) {
18618        synchronized (mPackages) {
18619            if (outInfo != null) {
18620                outInfo.uid = ps.appId;
18621            }
18622
18623            if (outInfo != null && outInfo.removedChildPackages != null) {
18624                final int childCount = (ps.childPackageNames != null)
18625                        ? ps.childPackageNames.size() : 0;
18626                for (int i = 0; i < childCount; i++) {
18627                    String childPackageName = ps.childPackageNames.get(i);
18628                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18629                    if (childPs == null) {
18630                        return false;
18631                    }
18632                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18633                            childPackageName);
18634                    if (childInfo != null) {
18635                        childInfo.uid = childPs.appId;
18636                    }
18637                }
18638            }
18639        }
18640
18641        // Delete package data from internal structures and also remove data if flag is set
18642        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18643
18644        // Delete the child packages data
18645        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18646        for (int i = 0; i < childCount; i++) {
18647            PackageSetting childPs;
18648            synchronized (mPackages) {
18649                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18650            }
18651            if (childPs != null) {
18652                PackageRemovedInfo childOutInfo = (outInfo != null
18653                        && outInfo.removedChildPackages != null)
18654                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18655                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18656                        && (replacingPackage != null
18657                        && !replacingPackage.hasChildPackage(childPs.name))
18658                        ? flags & ~DELETE_KEEP_DATA : flags;
18659                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18660                        deleteFlags, writeSettings);
18661            }
18662        }
18663
18664        // Delete application code and resources only for parent packages
18665        if (ps.parentPackageName == null) {
18666            if (deleteCodeAndResources && (outInfo != null)) {
18667                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18668                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18669                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18670            }
18671        }
18672
18673        return true;
18674    }
18675
18676    @Override
18677    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18678            int userId) {
18679        mContext.enforceCallingOrSelfPermission(
18680                android.Manifest.permission.DELETE_PACKAGES, null);
18681        synchronized (mPackages) {
18682            // Cannot block uninstall of static shared libs as they are
18683            // considered a part of the using app (emulating static linking).
18684            // Also static libs are installed always on internal storage.
18685            PackageParser.Package pkg = mPackages.get(packageName);
18686            if (pkg != null && pkg.staticSharedLibName != null) {
18687                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18688                        + " providing static shared library: " + pkg.staticSharedLibName);
18689                return false;
18690            }
18691            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18692            mSettings.writePackageRestrictionsLPr(userId);
18693        }
18694        return true;
18695    }
18696
18697    @Override
18698    public boolean getBlockUninstallForUser(String packageName, int userId) {
18699        synchronized (mPackages) {
18700            final PackageSetting ps = mSettings.mPackages.get(packageName);
18701            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18702                return false;
18703            }
18704            return mSettings.getBlockUninstallLPr(userId, packageName);
18705        }
18706    }
18707
18708    @Override
18709    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18710        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18711        synchronized (mPackages) {
18712            PackageSetting ps = mSettings.mPackages.get(packageName);
18713            if (ps == null) {
18714                Log.w(TAG, "Package doesn't exist: " + packageName);
18715                return false;
18716            }
18717            if (systemUserApp) {
18718                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18719            } else {
18720                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18721            }
18722            mSettings.writeLPr();
18723        }
18724        return true;
18725    }
18726
18727    /*
18728     * This method handles package deletion in general
18729     */
18730    private boolean deletePackageLIF(String packageName, UserHandle user,
18731            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18732            PackageRemovedInfo outInfo, boolean writeSettings,
18733            PackageParser.Package replacingPackage) {
18734        if (packageName == null) {
18735            Slog.w(TAG, "Attempt to delete null packageName.");
18736            return false;
18737        }
18738
18739        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18740
18741        PackageSetting ps;
18742        synchronized (mPackages) {
18743            ps = mSettings.mPackages.get(packageName);
18744            if (ps == null) {
18745                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18746                return false;
18747            }
18748
18749            if (ps.parentPackageName != null && (!isSystemApp(ps)
18750                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18751                if (DEBUG_REMOVE) {
18752                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18753                            + ((user == null) ? UserHandle.USER_ALL : user));
18754                }
18755                final int removedUserId = (user != null) ? user.getIdentifier()
18756                        : UserHandle.USER_ALL;
18757
18758                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18759                    return false;
18760                }
18761                markPackageUninstalledForUserLPw(ps, user);
18762                scheduleWritePackageRestrictionsLocked(user);
18763                return true;
18764            }
18765        }
18766
18767        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18768        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18769            unsuspendForSuspendingPackage(packageName, userId);
18770        }
18771
18772
18773        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18774                && user.getIdentifier() != UserHandle.USER_ALL)) {
18775            // The caller is asking that the package only be deleted for a single
18776            // user.  To do this, we just mark its uninstalled state and delete
18777            // its data. If this is a system app, we only allow this to happen if
18778            // they have set the special DELETE_SYSTEM_APP which requests different
18779            // semantics than normal for uninstalling system apps.
18780            markPackageUninstalledForUserLPw(ps, user);
18781
18782            if (!isSystemApp(ps)) {
18783                // Do not uninstall the APK if an app should be cached
18784                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18785                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18786                    // Other user still have this package installed, so all
18787                    // we need to do is clear this user's data and save that
18788                    // it is uninstalled.
18789                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18790                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18791                        return false;
18792                    }
18793                    scheduleWritePackageRestrictionsLocked(user);
18794                    return true;
18795                } else {
18796                    // We need to set it back to 'installed' so the uninstall
18797                    // broadcasts will be sent correctly.
18798                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18799                    ps.setInstalled(true, user.getIdentifier());
18800                    mSettings.writeKernelMappingLPr(ps);
18801                }
18802            } else {
18803                // This is a system app, so we assume that the
18804                // other users still have this package installed, so all
18805                // we need to do is clear this user's data and save that
18806                // it is uninstalled.
18807                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18808                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18809                    return false;
18810                }
18811                scheduleWritePackageRestrictionsLocked(user);
18812                return true;
18813            }
18814        }
18815
18816        // If we are deleting a composite package for all users, keep track
18817        // of result for each child.
18818        if (ps.childPackageNames != null && outInfo != null) {
18819            synchronized (mPackages) {
18820                final int childCount = ps.childPackageNames.size();
18821                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18822                for (int i = 0; i < childCount; i++) {
18823                    String childPackageName = ps.childPackageNames.get(i);
18824                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18825                    childInfo.removedPackage = childPackageName;
18826                    childInfo.installerPackageName = ps.installerPackageName;
18827                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18828                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18829                    if (childPs != null) {
18830                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18831                    }
18832                }
18833            }
18834        }
18835
18836        boolean ret = false;
18837        if (isSystemApp(ps)) {
18838            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18839            // When an updated system application is deleted we delete the existing resources
18840            // as well and fall back to existing code in system partition
18841            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18842        } else {
18843            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18844            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18845                    outInfo, writeSettings, replacingPackage);
18846        }
18847
18848        // Take a note whether we deleted the package for all users
18849        if (outInfo != null) {
18850            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18851            if (outInfo.removedChildPackages != null) {
18852                synchronized (mPackages) {
18853                    final int childCount = outInfo.removedChildPackages.size();
18854                    for (int i = 0; i < childCount; i++) {
18855                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18856                        if (childInfo != null) {
18857                            childInfo.removedForAllUsers = mPackages.get(
18858                                    childInfo.removedPackage) == null;
18859                        }
18860                    }
18861                }
18862            }
18863            // If we uninstalled an update to a system app there may be some
18864            // child packages that appeared as they are declared in the system
18865            // app but were not declared in the update.
18866            if (isSystemApp(ps)) {
18867                synchronized (mPackages) {
18868                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18869                    final int childCount = (updatedPs.childPackageNames != null)
18870                            ? updatedPs.childPackageNames.size() : 0;
18871                    for (int i = 0; i < childCount; i++) {
18872                        String childPackageName = updatedPs.childPackageNames.get(i);
18873                        if (outInfo.removedChildPackages == null
18874                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18875                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18876                            if (childPs == null) {
18877                                continue;
18878                            }
18879                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18880                            installRes.name = childPackageName;
18881                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18882                            installRes.pkg = mPackages.get(childPackageName);
18883                            installRes.uid = childPs.pkg.applicationInfo.uid;
18884                            if (outInfo.appearedChildPackages == null) {
18885                                outInfo.appearedChildPackages = new ArrayMap<>();
18886                            }
18887                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18888                        }
18889                    }
18890                }
18891            }
18892        }
18893
18894        return ret;
18895    }
18896
18897    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18898        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18899                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18900        for (int nextUserId : userIds) {
18901            if (DEBUG_REMOVE) {
18902                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18903            }
18904            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18905                    false /*installed*/,
18906                    true /*stopped*/,
18907                    true /*notLaunched*/,
18908                    false /*hidden*/,
18909                    false /*suspended*/,
18910                    null /*suspendingPackage*/,
18911                    null /*dialogMessage*/,
18912                    null /*suspendedAppExtras*/,
18913                    null /*suspendedLauncherExtras*/,
18914                    false /*instantApp*/,
18915                    false /*virtualPreload*/,
18916                    null /*lastDisableAppCaller*/,
18917                    null /*enabledComponents*/,
18918                    null /*disabledComponents*/,
18919                    ps.readUserState(nextUserId).domainVerificationStatus,
18920                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18921                    null /*harmfulAppWarning*/);
18922        }
18923        mSettings.writeKernelMappingLPr(ps);
18924    }
18925
18926    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18927            PackageRemovedInfo outInfo) {
18928        final PackageParser.Package pkg;
18929        synchronized (mPackages) {
18930            pkg = mPackages.get(ps.name);
18931        }
18932
18933        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18934                : new int[] {userId};
18935        for (int nextUserId : userIds) {
18936            if (DEBUG_REMOVE) {
18937                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18938                        + nextUserId);
18939            }
18940
18941            destroyAppDataLIF(pkg, userId,
18942                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18943            destroyAppProfilesLIF(pkg, userId);
18944            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18945            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18946            schedulePackageCleaning(ps.name, nextUserId, false);
18947            synchronized (mPackages) {
18948                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18949                    scheduleWritePackageRestrictionsLocked(nextUserId);
18950                }
18951                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18952            }
18953        }
18954
18955        if (outInfo != null) {
18956            outInfo.removedPackage = ps.name;
18957            outInfo.installerPackageName = ps.installerPackageName;
18958            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18959            outInfo.removedAppId = ps.appId;
18960            outInfo.removedUsers = userIds;
18961            outInfo.broadcastUsers = userIds;
18962        }
18963
18964        return true;
18965    }
18966
18967    private final class ClearStorageConnection implements ServiceConnection {
18968        IMediaContainerService mContainerService;
18969
18970        @Override
18971        public void onServiceConnected(ComponentName name, IBinder service) {
18972            synchronized (this) {
18973                mContainerService = IMediaContainerService.Stub
18974                        .asInterface(Binder.allowBlocking(service));
18975                notifyAll();
18976            }
18977        }
18978
18979        @Override
18980        public void onServiceDisconnected(ComponentName name) {
18981        }
18982    }
18983
18984    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18985        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18986
18987        final boolean mounted;
18988        if (Environment.isExternalStorageEmulated()) {
18989            mounted = true;
18990        } else {
18991            final String status = Environment.getExternalStorageState();
18992
18993            mounted = status.equals(Environment.MEDIA_MOUNTED)
18994                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18995        }
18996
18997        if (!mounted) {
18998            return;
18999        }
19000
19001        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19002        int[] users;
19003        if (userId == UserHandle.USER_ALL) {
19004            users = sUserManager.getUserIds();
19005        } else {
19006            users = new int[] { userId };
19007        }
19008        final ClearStorageConnection conn = new ClearStorageConnection();
19009        if (mContext.bindServiceAsUser(
19010                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19011            try {
19012                for (int curUser : users) {
19013                    long timeout = SystemClock.uptimeMillis() + 5000;
19014                    synchronized (conn) {
19015                        long now;
19016                        while (conn.mContainerService == null &&
19017                                (now = SystemClock.uptimeMillis()) < timeout) {
19018                            try {
19019                                conn.wait(timeout - now);
19020                            } catch (InterruptedException e) {
19021                            }
19022                        }
19023                    }
19024                    if (conn.mContainerService == null) {
19025                        return;
19026                    }
19027
19028                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19029                    clearDirectory(conn.mContainerService,
19030                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19031                    if (allData) {
19032                        clearDirectory(conn.mContainerService,
19033                                userEnv.buildExternalStorageAppDataDirs(packageName));
19034                        clearDirectory(conn.mContainerService,
19035                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19036                    }
19037                }
19038            } finally {
19039                mContext.unbindService(conn);
19040            }
19041        }
19042    }
19043
19044    @Override
19045    public void clearApplicationProfileData(String packageName) {
19046        enforceSystemOrRoot("Only the system can clear all profile data");
19047
19048        final PackageParser.Package pkg;
19049        synchronized (mPackages) {
19050            pkg = mPackages.get(packageName);
19051        }
19052
19053        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19054            synchronized (mInstallLock) {
19055                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19056            }
19057        }
19058    }
19059
19060    @Override
19061    public void clearApplicationUserData(final String packageName,
19062            final IPackageDataObserver observer, final int userId) {
19063        mContext.enforceCallingOrSelfPermission(
19064                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19065
19066        final int callingUid = Binder.getCallingUid();
19067        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19068                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19069
19070        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19071        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19072        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19073            throw new SecurityException("Cannot clear data for a protected package: "
19074                    + packageName);
19075        }
19076        // Queue up an async operation since the package deletion may take a little while.
19077        mHandler.post(new Runnable() {
19078            public void run() {
19079                mHandler.removeCallbacks(this);
19080                final boolean succeeded;
19081                if (!filterApp) {
19082                    try (PackageFreezer freezer = freezePackage(packageName,
19083                            "clearApplicationUserData")) {
19084                        synchronized (mInstallLock) {
19085                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19086                        }
19087                        clearExternalStorageDataSync(packageName, userId, true);
19088                        synchronized (mPackages) {
19089                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19090                                    packageName, userId);
19091                        }
19092                    }
19093                    if (succeeded) {
19094                        // invoke DeviceStorageMonitor's update method to clear any notifications
19095                        DeviceStorageMonitorInternal dsm = LocalServices
19096                                .getService(DeviceStorageMonitorInternal.class);
19097                        if (dsm != null) {
19098                            dsm.checkMemory();
19099                        }
19100                        if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
19101                                == PERMISSION_GRANTED) {
19102                            unsuspendForSuspendingPackage(packageName, userId);
19103                        }
19104                    }
19105                } else {
19106                    succeeded = false;
19107                }
19108                if (observer != null) {
19109                    try {
19110                        observer.onRemoveCompleted(packageName, succeeded);
19111                    } catch (RemoteException e) {
19112                        Log.i(TAG, "Observer no longer exists.");
19113                    }
19114                } //end if observer
19115            } //end run
19116        });
19117    }
19118
19119    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19120        if (packageName == null) {
19121            Slog.w(TAG, "Attempt to delete null packageName.");
19122            return false;
19123        }
19124
19125        // Try finding details about the requested package
19126        PackageParser.Package pkg;
19127        synchronized (mPackages) {
19128            pkg = mPackages.get(packageName);
19129            if (pkg == null) {
19130                final PackageSetting ps = mSettings.mPackages.get(packageName);
19131                if (ps != null) {
19132                    pkg = ps.pkg;
19133                }
19134            }
19135
19136            if (pkg == null) {
19137                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19138                return false;
19139            }
19140
19141            PackageSetting ps = (PackageSetting) pkg.mExtras;
19142            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19143        }
19144
19145        clearAppDataLIF(pkg, userId,
19146                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19147
19148        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19149        removeKeystoreDataIfNeeded(userId, appId);
19150
19151        UserManagerInternal umInternal = getUserManagerInternal();
19152        final int flags;
19153        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19154            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19155        } else if (umInternal.isUserRunning(userId)) {
19156            flags = StorageManager.FLAG_STORAGE_DE;
19157        } else {
19158            flags = 0;
19159        }
19160        prepareAppDataContentsLIF(pkg, userId, flags);
19161
19162        return true;
19163    }
19164
19165    /**
19166     * Reverts user permission state changes (permissions and flags) in
19167     * all packages for a given user.
19168     *
19169     * @param userId The device user for which to do a reset.
19170     */
19171    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19172        final int packageCount = mPackages.size();
19173        for (int i = 0; i < packageCount; i++) {
19174            PackageParser.Package pkg = mPackages.valueAt(i);
19175            PackageSetting ps = (PackageSetting) pkg.mExtras;
19176            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19177        }
19178    }
19179
19180    private void resetNetworkPolicies(int userId) {
19181        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19182    }
19183
19184    /**
19185     * Reverts user permission state changes (permissions and flags).
19186     *
19187     * @param ps The package for which to reset.
19188     * @param userId The device user for which to do a reset.
19189     */
19190    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19191            final PackageSetting ps, final int userId) {
19192        if (ps.pkg == null) {
19193            return;
19194        }
19195
19196        // These are flags that can change base on user actions.
19197        final int userSettableMask = FLAG_PERMISSION_USER_SET
19198                | FLAG_PERMISSION_USER_FIXED
19199                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19200                | FLAG_PERMISSION_REVIEW_REQUIRED;
19201
19202        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19203                | FLAG_PERMISSION_POLICY_FIXED;
19204
19205        boolean writeInstallPermissions = false;
19206        boolean writeRuntimePermissions = false;
19207
19208        final int permissionCount = ps.pkg.requestedPermissions.size();
19209        for (int i = 0; i < permissionCount; i++) {
19210            final String permName = ps.pkg.requestedPermissions.get(i);
19211            final BasePermission bp =
19212                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19213            if (bp == null) {
19214                continue;
19215            }
19216
19217            // If shared user we just reset the state to which only this app contributed.
19218            if (ps.sharedUser != null) {
19219                boolean used = false;
19220                final int packageCount = ps.sharedUser.packages.size();
19221                for (int j = 0; j < packageCount; j++) {
19222                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19223                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19224                            && pkg.pkg.requestedPermissions.contains(permName)) {
19225                        used = true;
19226                        break;
19227                    }
19228                }
19229                if (used) {
19230                    continue;
19231                }
19232            }
19233
19234            final PermissionsState permissionsState = ps.getPermissionsState();
19235
19236            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19237
19238            // Always clear the user settable flags.
19239            final boolean hasInstallState =
19240                    permissionsState.getInstallPermissionState(permName) != null;
19241            // If permission review is enabled and this is a legacy app, mark the
19242            // permission as requiring a review as this is the initial state.
19243            int flags = 0;
19244            if (mSettings.mPermissions.mPermissionReviewRequired
19245                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19246                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19247            }
19248            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19249                if (hasInstallState) {
19250                    writeInstallPermissions = true;
19251                } else {
19252                    writeRuntimePermissions = true;
19253                }
19254            }
19255
19256            // Below is only runtime permission handling.
19257            if (!bp.isRuntime()) {
19258                continue;
19259            }
19260
19261            // Never clobber system or policy.
19262            if ((oldFlags & policyOrSystemFlags) != 0) {
19263                continue;
19264            }
19265
19266            // If this permission was granted by default, make sure it is.
19267            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19268                if (permissionsState.grantRuntimePermission(bp, userId)
19269                        != PERMISSION_OPERATION_FAILURE) {
19270                    writeRuntimePermissions = true;
19271                }
19272            // If permission review is enabled the permissions for a legacy apps
19273            // are represented as constantly granted runtime ones, so don't revoke.
19274            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19275                // Otherwise, reset the permission.
19276                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19277                switch (revokeResult) {
19278                    case PERMISSION_OPERATION_SUCCESS:
19279                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19280                        writeRuntimePermissions = true;
19281                        final int appId = ps.appId;
19282                        mHandler.post(new Runnable() {
19283                            @Override
19284                            public void run() {
19285                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19286                            }
19287                        });
19288                    } break;
19289                }
19290            }
19291        }
19292
19293        // Synchronously write as we are taking permissions away.
19294        if (writeRuntimePermissions) {
19295            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19296        }
19297
19298        // Synchronously write as we are taking permissions away.
19299        if (writeInstallPermissions) {
19300            mSettings.writeLPr();
19301        }
19302    }
19303
19304    /**
19305     * Remove entries from the keystore daemon. Will only remove it if the
19306     * {@code appId} is valid.
19307     */
19308    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19309        if (appId < 0) {
19310            return;
19311        }
19312
19313        final KeyStore keyStore = KeyStore.getInstance();
19314        if (keyStore != null) {
19315            if (userId == UserHandle.USER_ALL) {
19316                for (final int individual : sUserManager.getUserIds()) {
19317                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19318                }
19319            } else {
19320                keyStore.clearUid(UserHandle.getUid(userId, appId));
19321            }
19322        } else {
19323            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19324        }
19325    }
19326
19327    @Override
19328    public void deleteApplicationCacheFiles(final String packageName,
19329            final IPackageDataObserver observer) {
19330        final int userId = UserHandle.getCallingUserId();
19331        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19332    }
19333
19334    @Override
19335    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19336            final IPackageDataObserver observer) {
19337        final int callingUid = Binder.getCallingUid();
19338        if (mContext.checkCallingOrSelfPermission(
19339                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19340                != PackageManager.PERMISSION_GRANTED) {
19341            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19342            if (mContext.checkCallingOrSelfPermission(
19343                    android.Manifest.permission.DELETE_CACHE_FILES)
19344                    == PackageManager.PERMISSION_GRANTED) {
19345                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19346                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19347                        ", silently ignoring");
19348                return;
19349            }
19350            mContext.enforceCallingOrSelfPermission(
19351                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19352        }
19353        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19354                /* requireFullPermission= */ true, /* checkShell= */ false,
19355                "delete application cache files");
19356        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19357                android.Manifest.permission.ACCESS_INSTANT_APPS);
19358
19359        final PackageParser.Package pkg;
19360        synchronized (mPackages) {
19361            pkg = mPackages.get(packageName);
19362        }
19363
19364        // Queue up an async operation since the package deletion may take a little while.
19365        mHandler.post(new Runnable() {
19366            public void run() {
19367                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19368                boolean doClearData = true;
19369                if (ps != null) {
19370                    final boolean targetIsInstantApp =
19371                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19372                    doClearData = !targetIsInstantApp
19373                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19374                }
19375                if (doClearData) {
19376                    synchronized (mInstallLock) {
19377                        final int flags = StorageManager.FLAG_STORAGE_DE
19378                                | StorageManager.FLAG_STORAGE_CE;
19379                        // We're only clearing cache files, so we don't care if the
19380                        // app is unfrozen and still able to run
19381                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19382                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19383                    }
19384                    clearExternalStorageDataSync(packageName, userId, false);
19385                }
19386                if (observer != null) {
19387                    try {
19388                        observer.onRemoveCompleted(packageName, true);
19389                    } catch (RemoteException e) {
19390                        Log.i(TAG, "Observer no longer exists.");
19391                    }
19392                }
19393            }
19394        });
19395    }
19396
19397    @Override
19398    public void getPackageSizeInfo(final String packageName, int userHandle,
19399            final IPackageStatsObserver observer) {
19400        throw new UnsupportedOperationException(
19401                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19402    }
19403
19404    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19405        final PackageSetting ps;
19406        synchronized (mPackages) {
19407            ps = mSettings.mPackages.get(packageName);
19408            if (ps == null) {
19409                Slog.w(TAG, "Failed to find settings for " + packageName);
19410                return false;
19411            }
19412        }
19413
19414        final String[] packageNames = { packageName };
19415        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19416        final String[] codePaths = { ps.codePathString };
19417
19418        try {
19419            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19420                    ps.appId, ceDataInodes, codePaths, stats);
19421
19422            // For now, ignore code size of packages on system partition
19423            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19424                stats.codeSize = 0;
19425            }
19426
19427            // External clients expect these to be tracked separately
19428            stats.dataSize -= stats.cacheSize;
19429
19430        } catch (InstallerException e) {
19431            Slog.w(TAG, String.valueOf(e));
19432            return false;
19433        }
19434
19435        return true;
19436    }
19437
19438    private int getUidTargetSdkVersionLockedLPr(int uid) {
19439        Object obj = mSettings.getUserIdLPr(uid);
19440        if (obj instanceof SharedUserSetting) {
19441            final SharedUserSetting sus = (SharedUserSetting) obj;
19442            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19443            final Iterator<PackageSetting> it = sus.packages.iterator();
19444            while (it.hasNext()) {
19445                final PackageSetting ps = it.next();
19446                if (ps.pkg != null) {
19447                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19448                    if (v < vers) vers = v;
19449                }
19450            }
19451            return vers;
19452        } else if (obj instanceof PackageSetting) {
19453            final PackageSetting ps = (PackageSetting) obj;
19454            if (ps.pkg != null) {
19455                return ps.pkg.applicationInfo.targetSdkVersion;
19456            }
19457        }
19458        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19459    }
19460
19461    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19462        final PackageParser.Package p = mPackages.get(packageName);
19463        if (p != null) {
19464            return p.applicationInfo.targetSdkVersion;
19465        }
19466        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19467    }
19468
19469    @Override
19470    public void addPreferredActivity(IntentFilter filter, int match,
19471            ComponentName[] set, ComponentName activity, int userId) {
19472        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19473                "Adding preferred");
19474    }
19475
19476    private void addPreferredActivityInternal(IntentFilter filter, int match,
19477            ComponentName[] set, ComponentName activity, boolean always, int userId,
19478            String opname) {
19479        // writer
19480        int callingUid = Binder.getCallingUid();
19481        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19482                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19483        if (filter.countActions() == 0) {
19484            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19485            return;
19486        }
19487        synchronized (mPackages) {
19488            if (mContext.checkCallingOrSelfPermission(
19489                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19490                    != PackageManager.PERMISSION_GRANTED) {
19491                if (getUidTargetSdkVersionLockedLPr(callingUid)
19492                        < Build.VERSION_CODES.FROYO) {
19493                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19494                            + callingUid);
19495                    return;
19496                }
19497                mContext.enforceCallingOrSelfPermission(
19498                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19499            }
19500
19501            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19502            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19503                    + userId + ":");
19504            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19505            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19506            scheduleWritePackageRestrictionsLocked(userId);
19507            postPreferredActivityChangedBroadcast(userId);
19508        }
19509    }
19510
19511    private void postPreferredActivityChangedBroadcast(int userId) {
19512        mHandler.post(() -> {
19513            final IActivityManager am = ActivityManager.getService();
19514            if (am == null) {
19515                return;
19516            }
19517
19518            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19519            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19520            try {
19521                am.broadcastIntent(null, intent, null, null,
19522                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19523                        null, false, false, userId);
19524            } catch (RemoteException e) {
19525            }
19526        });
19527    }
19528
19529    @Override
19530    public void replacePreferredActivity(IntentFilter filter, int match,
19531            ComponentName[] set, ComponentName activity, int userId) {
19532        if (filter.countActions() != 1) {
19533            throw new IllegalArgumentException(
19534                    "replacePreferredActivity expects filter to have only 1 action.");
19535        }
19536        if (filter.countDataAuthorities() != 0
19537                || filter.countDataPaths() != 0
19538                || filter.countDataSchemes() > 1
19539                || filter.countDataTypes() != 0) {
19540            throw new IllegalArgumentException(
19541                    "replacePreferredActivity expects filter to have no data authorities, " +
19542                    "paths, or types; and at most one scheme.");
19543        }
19544
19545        final int callingUid = Binder.getCallingUid();
19546        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19547                true /* requireFullPermission */, false /* checkShell */,
19548                "replace preferred activity");
19549        synchronized (mPackages) {
19550            if (mContext.checkCallingOrSelfPermission(
19551                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19552                    != PackageManager.PERMISSION_GRANTED) {
19553                if (getUidTargetSdkVersionLockedLPr(callingUid)
19554                        < Build.VERSION_CODES.FROYO) {
19555                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19556                            + Binder.getCallingUid());
19557                    return;
19558                }
19559                mContext.enforceCallingOrSelfPermission(
19560                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19561            }
19562
19563            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19564            if (pir != null) {
19565                // Get all of the existing entries that exactly match this filter.
19566                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19567                if (existing != null && existing.size() == 1) {
19568                    PreferredActivity cur = existing.get(0);
19569                    if (DEBUG_PREFERRED) {
19570                        Slog.i(TAG, "Checking replace of preferred:");
19571                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19572                        if (!cur.mPref.mAlways) {
19573                            Slog.i(TAG, "  -- CUR; not mAlways!");
19574                        } else {
19575                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19576                            Slog.i(TAG, "  -- CUR: mSet="
19577                                    + Arrays.toString(cur.mPref.mSetComponents));
19578                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19579                            Slog.i(TAG, "  -- NEW: mMatch="
19580                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19581                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19582                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19583                        }
19584                    }
19585                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19586                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19587                            && cur.mPref.sameSet(set)) {
19588                        // Setting the preferred activity to what it happens to be already
19589                        if (DEBUG_PREFERRED) {
19590                            Slog.i(TAG, "Replacing with same preferred activity "
19591                                    + cur.mPref.mShortComponent + " for user "
19592                                    + userId + ":");
19593                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19594                        }
19595                        return;
19596                    }
19597                }
19598
19599                if (existing != null) {
19600                    if (DEBUG_PREFERRED) {
19601                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19602                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19603                    }
19604                    for (int i = 0; i < existing.size(); i++) {
19605                        PreferredActivity pa = existing.get(i);
19606                        if (DEBUG_PREFERRED) {
19607                            Slog.i(TAG, "Removing existing preferred activity "
19608                                    + pa.mPref.mComponent + ":");
19609                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19610                        }
19611                        pir.removeFilter(pa);
19612                    }
19613                }
19614            }
19615            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19616                    "Replacing preferred");
19617        }
19618    }
19619
19620    @Override
19621    public void clearPackagePreferredActivities(String packageName) {
19622        final int callingUid = Binder.getCallingUid();
19623        if (getInstantAppPackageName(callingUid) != null) {
19624            return;
19625        }
19626        // writer
19627        synchronized (mPackages) {
19628            PackageParser.Package pkg = mPackages.get(packageName);
19629            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19630                if (mContext.checkCallingOrSelfPermission(
19631                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19632                        != PackageManager.PERMISSION_GRANTED) {
19633                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19634                            < Build.VERSION_CODES.FROYO) {
19635                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19636                                + callingUid);
19637                        return;
19638                    }
19639                    mContext.enforceCallingOrSelfPermission(
19640                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19641                }
19642            }
19643            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19644            if (ps != null
19645                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19646                return;
19647            }
19648            int user = UserHandle.getCallingUserId();
19649            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19650                scheduleWritePackageRestrictionsLocked(user);
19651            }
19652        }
19653    }
19654
19655    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19656    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19657        ArrayList<PreferredActivity> removed = null;
19658        boolean changed = false;
19659        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19660            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19661            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19662            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19663                continue;
19664            }
19665            Iterator<PreferredActivity> it = pir.filterIterator();
19666            while (it.hasNext()) {
19667                PreferredActivity pa = it.next();
19668                // Mark entry for removal only if it matches the package name
19669                // and the entry is of type "always".
19670                if (packageName == null ||
19671                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19672                                && pa.mPref.mAlways)) {
19673                    if (removed == null) {
19674                        removed = new ArrayList<PreferredActivity>();
19675                    }
19676                    removed.add(pa);
19677                }
19678            }
19679            if (removed != null) {
19680                for (int j=0; j<removed.size(); j++) {
19681                    PreferredActivity pa = removed.get(j);
19682                    pir.removeFilter(pa);
19683                }
19684                changed = true;
19685            }
19686        }
19687        if (changed) {
19688            postPreferredActivityChangedBroadcast(userId);
19689        }
19690        return changed;
19691    }
19692
19693    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19694    private void clearIntentFilterVerificationsLPw(int userId) {
19695        final int packageCount = mPackages.size();
19696        for (int i = 0; i < packageCount; i++) {
19697            PackageParser.Package pkg = mPackages.valueAt(i);
19698            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19699        }
19700    }
19701
19702    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19703    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19704        if (userId == UserHandle.USER_ALL) {
19705            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19706                    sUserManager.getUserIds())) {
19707                for (int oneUserId : sUserManager.getUserIds()) {
19708                    scheduleWritePackageRestrictionsLocked(oneUserId);
19709                }
19710            }
19711        } else {
19712            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19713                scheduleWritePackageRestrictionsLocked(userId);
19714            }
19715        }
19716    }
19717
19718    /** Clears state for all users, and touches intent filter verification policy */
19719    void clearDefaultBrowserIfNeeded(String packageName) {
19720        for (int oneUserId : sUserManager.getUserIds()) {
19721            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19722        }
19723    }
19724
19725    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19726        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19727        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19728            if (packageName.equals(defaultBrowserPackageName)) {
19729                setDefaultBrowserPackageName(null, userId);
19730            }
19731        }
19732    }
19733
19734    @Override
19735    public void resetApplicationPreferences(int userId) {
19736        mContext.enforceCallingOrSelfPermission(
19737                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19738        final long identity = Binder.clearCallingIdentity();
19739        // writer
19740        try {
19741            synchronized (mPackages) {
19742                clearPackagePreferredActivitiesLPw(null, userId);
19743                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19744                // TODO: We have to reset the default SMS and Phone. This requires
19745                // significant refactoring to keep all default apps in the package
19746                // manager (cleaner but more work) or have the services provide
19747                // callbacks to the package manager to request a default app reset.
19748                applyFactoryDefaultBrowserLPw(userId);
19749                clearIntentFilterVerificationsLPw(userId);
19750                primeDomainVerificationsLPw(userId);
19751                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19752                scheduleWritePackageRestrictionsLocked(userId);
19753            }
19754            resetNetworkPolicies(userId);
19755        } finally {
19756            Binder.restoreCallingIdentity(identity);
19757        }
19758    }
19759
19760    @Override
19761    public int getPreferredActivities(List<IntentFilter> outFilters,
19762            List<ComponentName> outActivities, String packageName) {
19763        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19764            return 0;
19765        }
19766        int num = 0;
19767        final int userId = UserHandle.getCallingUserId();
19768        // reader
19769        synchronized (mPackages) {
19770            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19771            if (pir != null) {
19772                final Iterator<PreferredActivity> it = pir.filterIterator();
19773                while (it.hasNext()) {
19774                    final PreferredActivity pa = it.next();
19775                    if (packageName == null
19776                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19777                                    && pa.mPref.mAlways)) {
19778                        if (outFilters != null) {
19779                            outFilters.add(new IntentFilter(pa));
19780                        }
19781                        if (outActivities != null) {
19782                            outActivities.add(pa.mPref.mComponent);
19783                        }
19784                    }
19785                }
19786            }
19787        }
19788
19789        return num;
19790    }
19791
19792    @Override
19793    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19794            int userId) {
19795        int callingUid = Binder.getCallingUid();
19796        if (callingUid != Process.SYSTEM_UID) {
19797            throw new SecurityException(
19798                    "addPersistentPreferredActivity can only be run by the system");
19799        }
19800        if (filter.countActions() == 0) {
19801            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19802            return;
19803        }
19804        synchronized (mPackages) {
19805            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19806                    ":");
19807            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19808            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19809                    new PersistentPreferredActivity(filter, activity));
19810            scheduleWritePackageRestrictionsLocked(userId);
19811            postPreferredActivityChangedBroadcast(userId);
19812        }
19813    }
19814
19815    @Override
19816    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19817        int callingUid = Binder.getCallingUid();
19818        if (callingUid != Process.SYSTEM_UID) {
19819            throw new SecurityException(
19820                    "clearPackagePersistentPreferredActivities can only be run by the system");
19821        }
19822        ArrayList<PersistentPreferredActivity> removed = null;
19823        boolean changed = false;
19824        synchronized (mPackages) {
19825            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19826                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19827                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19828                        .valueAt(i);
19829                if (userId != thisUserId) {
19830                    continue;
19831                }
19832                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19833                while (it.hasNext()) {
19834                    PersistentPreferredActivity ppa = it.next();
19835                    // Mark entry for removal only if it matches the package name.
19836                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19837                        if (removed == null) {
19838                            removed = new ArrayList<PersistentPreferredActivity>();
19839                        }
19840                        removed.add(ppa);
19841                    }
19842                }
19843                if (removed != null) {
19844                    for (int j=0; j<removed.size(); j++) {
19845                        PersistentPreferredActivity ppa = removed.get(j);
19846                        ppir.removeFilter(ppa);
19847                    }
19848                    changed = true;
19849                }
19850            }
19851
19852            if (changed) {
19853                scheduleWritePackageRestrictionsLocked(userId);
19854                postPreferredActivityChangedBroadcast(userId);
19855            }
19856        }
19857    }
19858
19859    /**
19860     * Common machinery for picking apart a restored XML blob and passing
19861     * it to a caller-supplied functor to be applied to the running system.
19862     */
19863    private void restoreFromXml(XmlPullParser parser, int userId,
19864            String expectedStartTag, BlobXmlRestorer functor)
19865            throws IOException, XmlPullParserException {
19866        int type;
19867        while ((type = parser.next()) != XmlPullParser.START_TAG
19868                && type != XmlPullParser.END_DOCUMENT) {
19869        }
19870        if (type != XmlPullParser.START_TAG) {
19871            // oops didn't find a start tag?!
19872            if (DEBUG_BACKUP) {
19873                Slog.e(TAG, "Didn't find start tag during restore");
19874            }
19875            return;
19876        }
19877Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19878        // this is supposed to be TAG_PREFERRED_BACKUP
19879        if (!expectedStartTag.equals(parser.getName())) {
19880            if (DEBUG_BACKUP) {
19881                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19882            }
19883            return;
19884        }
19885
19886        // skip interfering stuff, then we're aligned with the backing implementation
19887        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19888Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19889        functor.apply(parser, userId);
19890    }
19891
19892    private interface BlobXmlRestorer {
19893        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19894    }
19895
19896    /**
19897     * Non-Binder method, support for the backup/restore mechanism: write the
19898     * full set of preferred activities in its canonical XML format.  Returns the
19899     * XML output as a byte array, or null if there is none.
19900     */
19901    @Override
19902    public byte[] getPreferredActivityBackup(int userId) {
19903        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19904            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19905        }
19906
19907        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19908        try {
19909            final XmlSerializer serializer = new FastXmlSerializer();
19910            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19911            serializer.startDocument(null, true);
19912            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19913
19914            synchronized (mPackages) {
19915                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19916            }
19917
19918            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19919            serializer.endDocument();
19920            serializer.flush();
19921        } catch (Exception e) {
19922            if (DEBUG_BACKUP) {
19923                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19924            }
19925            return null;
19926        }
19927
19928        return dataStream.toByteArray();
19929    }
19930
19931    @Override
19932    public void restorePreferredActivities(byte[] backup, int userId) {
19933        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19934            throw new SecurityException("Only the system may call restorePreferredActivities()");
19935        }
19936
19937        try {
19938            final XmlPullParser parser = Xml.newPullParser();
19939            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19940            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19941                    new BlobXmlRestorer() {
19942                        @Override
19943                        public void apply(XmlPullParser parser, int userId)
19944                                throws XmlPullParserException, IOException {
19945                            synchronized (mPackages) {
19946                                mSettings.readPreferredActivitiesLPw(parser, userId);
19947                            }
19948                        }
19949                    } );
19950        } catch (Exception e) {
19951            if (DEBUG_BACKUP) {
19952                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19953            }
19954        }
19955    }
19956
19957    /**
19958     * Non-Binder method, support for the backup/restore mechanism: write the
19959     * default browser (etc) settings in its canonical XML format.  Returns the default
19960     * browser XML representation as a byte array, or null if there is none.
19961     */
19962    @Override
19963    public byte[] getDefaultAppsBackup(int userId) {
19964        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19965            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19966        }
19967
19968        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19969        try {
19970            final XmlSerializer serializer = new FastXmlSerializer();
19971            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19972            serializer.startDocument(null, true);
19973            serializer.startTag(null, TAG_DEFAULT_APPS);
19974
19975            synchronized (mPackages) {
19976                mSettings.writeDefaultAppsLPr(serializer, userId);
19977            }
19978
19979            serializer.endTag(null, TAG_DEFAULT_APPS);
19980            serializer.endDocument();
19981            serializer.flush();
19982        } catch (Exception e) {
19983            if (DEBUG_BACKUP) {
19984                Slog.e(TAG, "Unable to write default apps for backup", e);
19985            }
19986            return null;
19987        }
19988
19989        return dataStream.toByteArray();
19990    }
19991
19992    @Override
19993    public void restoreDefaultApps(byte[] backup, int userId) {
19994        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19995            throw new SecurityException("Only the system may call restoreDefaultApps()");
19996        }
19997
19998        try {
19999            final XmlPullParser parser = Xml.newPullParser();
20000            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20001            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20002                    new BlobXmlRestorer() {
20003                        @Override
20004                        public void apply(XmlPullParser parser, int userId)
20005                                throws XmlPullParserException, IOException {
20006                            synchronized (mPackages) {
20007                                mSettings.readDefaultAppsLPw(parser, userId);
20008                            }
20009                        }
20010                    } );
20011        } catch (Exception e) {
20012            if (DEBUG_BACKUP) {
20013                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20014            }
20015        }
20016    }
20017
20018    @Override
20019    public byte[] getIntentFilterVerificationBackup(int userId) {
20020        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20021            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20022        }
20023
20024        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20025        try {
20026            final XmlSerializer serializer = new FastXmlSerializer();
20027            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20028            serializer.startDocument(null, true);
20029            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20030
20031            synchronized (mPackages) {
20032                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20033            }
20034
20035            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20036            serializer.endDocument();
20037            serializer.flush();
20038        } catch (Exception e) {
20039            if (DEBUG_BACKUP) {
20040                Slog.e(TAG, "Unable to write default apps for backup", e);
20041            }
20042            return null;
20043        }
20044
20045        return dataStream.toByteArray();
20046    }
20047
20048    @Override
20049    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20050        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20051            throw new SecurityException("Only the system may call restorePreferredActivities()");
20052        }
20053
20054        try {
20055            final XmlPullParser parser = Xml.newPullParser();
20056            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20057            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20058                    new BlobXmlRestorer() {
20059                        @Override
20060                        public void apply(XmlPullParser parser, int userId)
20061                                throws XmlPullParserException, IOException {
20062                            synchronized (mPackages) {
20063                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20064                                mSettings.writeLPr();
20065                            }
20066                        }
20067                    } );
20068        } catch (Exception e) {
20069            if (DEBUG_BACKUP) {
20070                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20071            }
20072        }
20073    }
20074
20075    @Override
20076    public byte[] getPermissionGrantBackup(int userId) {
20077        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20078            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20079        }
20080
20081        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20082        try {
20083            final XmlSerializer serializer = new FastXmlSerializer();
20084            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20085            serializer.startDocument(null, true);
20086            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20087
20088            synchronized (mPackages) {
20089                serializeRuntimePermissionGrantsLPr(serializer, userId);
20090            }
20091
20092            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20093            serializer.endDocument();
20094            serializer.flush();
20095        } catch (Exception e) {
20096            if (DEBUG_BACKUP) {
20097                Slog.e(TAG, "Unable to write default apps for backup", e);
20098            }
20099            return null;
20100        }
20101
20102        return dataStream.toByteArray();
20103    }
20104
20105    @Override
20106    public void restorePermissionGrants(byte[] backup, int userId) {
20107        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20108            throw new SecurityException("Only the system may call restorePermissionGrants()");
20109        }
20110
20111        try {
20112            final XmlPullParser parser = Xml.newPullParser();
20113            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20114            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20115                    new BlobXmlRestorer() {
20116                        @Override
20117                        public void apply(XmlPullParser parser, int userId)
20118                                throws XmlPullParserException, IOException {
20119                            synchronized (mPackages) {
20120                                processRestoredPermissionGrantsLPr(parser, userId);
20121                            }
20122                        }
20123                    } );
20124        } catch (Exception e) {
20125            if (DEBUG_BACKUP) {
20126                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20127            }
20128        }
20129    }
20130
20131    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20132            throws IOException {
20133        serializer.startTag(null, TAG_ALL_GRANTS);
20134
20135        final int N = mSettings.mPackages.size();
20136        for (int i = 0; i < N; i++) {
20137            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20138            boolean pkgGrantsKnown = false;
20139
20140            PermissionsState packagePerms = ps.getPermissionsState();
20141
20142            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20143                final int grantFlags = state.getFlags();
20144                // only look at grants that are not system/policy fixed
20145                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20146                    final boolean isGranted = state.isGranted();
20147                    // And only back up the user-twiddled state bits
20148                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20149                        final String packageName = mSettings.mPackages.keyAt(i);
20150                        if (!pkgGrantsKnown) {
20151                            serializer.startTag(null, TAG_GRANT);
20152                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20153                            pkgGrantsKnown = true;
20154                        }
20155
20156                        final boolean userSet =
20157                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20158                        final boolean userFixed =
20159                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20160                        final boolean revoke =
20161                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20162
20163                        serializer.startTag(null, TAG_PERMISSION);
20164                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20165                        if (isGranted) {
20166                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20167                        }
20168                        if (userSet) {
20169                            serializer.attribute(null, ATTR_USER_SET, "true");
20170                        }
20171                        if (userFixed) {
20172                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20173                        }
20174                        if (revoke) {
20175                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20176                        }
20177                        serializer.endTag(null, TAG_PERMISSION);
20178                    }
20179                }
20180            }
20181
20182            if (pkgGrantsKnown) {
20183                serializer.endTag(null, TAG_GRANT);
20184            }
20185        }
20186
20187        serializer.endTag(null, TAG_ALL_GRANTS);
20188    }
20189
20190    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20191            throws XmlPullParserException, IOException {
20192        String pkgName = null;
20193        int outerDepth = parser.getDepth();
20194        int type;
20195        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20196                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20197            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20198                continue;
20199            }
20200
20201            final String tagName = parser.getName();
20202            if (tagName.equals(TAG_GRANT)) {
20203                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20204                if (DEBUG_BACKUP) {
20205                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20206                }
20207            } else if (tagName.equals(TAG_PERMISSION)) {
20208
20209                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20210                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20211
20212                int newFlagSet = 0;
20213                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20214                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20215                }
20216                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20217                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20218                }
20219                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20220                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20221                }
20222                if (DEBUG_BACKUP) {
20223                    Slog.v(TAG, "  + Restoring grant:"
20224                            + " pkg=" + pkgName
20225                            + " perm=" + permName
20226                            + " granted=" + isGranted
20227                            + " bits=0x" + Integer.toHexString(newFlagSet));
20228                }
20229                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20230                if (ps != null) {
20231                    // Already installed so we apply the grant immediately
20232                    if (DEBUG_BACKUP) {
20233                        Slog.v(TAG, "        + already installed; applying");
20234                    }
20235                    PermissionsState perms = ps.getPermissionsState();
20236                    BasePermission bp =
20237                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20238                    if (bp != null) {
20239                        if (isGranted) {
20240                            perms.grantRuntimePermission(bp, userId);
20241                        }
20242                        if (newFlagSet != 0) {
20243                            perms.updatePermissionFlags(
20244                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20245                        }
20246                    }
20247                } else {
20248                    // Need to wait for post-restore install to apply the grant
20249                    if (DEBUG_BACKUP) {
20250                        Slog.v(TAG, "        - not yet installed; saving for later");
20251                    }
20252                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20253                            isGranted, newFlagSet, userId);
20254                }
20255            } else {
20256                PackageManagerService.reportSettingsProblem(Log.WARN,
20257                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20258                XmlUtils.skipCurrentTag(parser);
20259            }
20260        }
20261
20262        scheduleWriteSettingsLocked();
20263        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20264    }
20265
20266    @Override
20267    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20268            int sourceUserId, int targetUserId, int flags) {
20269        mContext.enforceCallingOrSelfPermission(
20270                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20271        int callingUid = Binder.getCallingUid();
20272        enforceOwnerRights(ownerPackage, callingUid);
20273        PackageManagerServiceUtils.enforceShellRestriction(
20274                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20275        if (intentFilter.countActions() == 0) {
20276            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20277            return;
20278        }
20279        synchronized (mPackages) {
20280            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20281                    ownerPackage, targetUserId, flags);
20282            CrossProfileIntentResolver resolver =
20283                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20284            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20285            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20286            if (existing != null) {
20287                int size = existing.size();
20288                for (int i = 0; i < size; i++) {
20289                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20290                        return;
20291                    }
20292                }
20293            }
20294            resolver.addFilter(newFilter);
20295            scheduleWritePackageRestrictionsLocked(sourceUserId);
20296        }
20297    }
20298
20299    @Override
20300    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20301        mContext.enforceCallingOrSelfPermission(
20302                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20303        final int callingUid = Binder.getCallingUid();
20304        enforceOwnerRights(ownerPackage, callingUid);
20305        PackageManagerServiceUtils.enforceShellRestriction(
20306                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20307        synchronized (mPackages) {
20308            CrossProfileIntentResolver resolver =
20309                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20310            ArraySet<CrossProfileIntentFilter> set =
20311                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20312            for (CrossProfileIntentFilter filter : set) {
20313                if (filter.getOwnerPackage().equals(ownerPackage)) {
20314                    resolver.removeFilter(filter);
20315                }
20316            }
20317            scheduleWritePackageRestrictionsLocked(sourceUserId);
20318        }
20319    }
20320
20321    // Enforcing that callingUid is owning pkg on userId
20322    private void enforceOwnerRights(String pkg, int callingUid) {
20323        // The system owns everything.
20324        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20325            return;
20326        }
20327        final int callingUserId = UserHandle.getUserId(callingUid);
20328        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20329        if (pi == null) {
20330            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20331                    + callingUserId);
20332        }
20333        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20334            throw new SecurityException("Calling uid " + callingUid
20335                    + " does not own package " + pkg);
20336        }
20337    }
20338
20339    @Override
20340    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20341        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20342            return null;
20343        }
20344        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20345    }
20346
20347    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20348        UserManagerService ums = UserManagerService.getInstance();
20349        if (ums != null) {
20350            final UserInfo parent = ums.getProfileParent(userId);
20351            final int launcherUid = (parent != null) ? parent.id : userId;
20352            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20353            if (launcherComponent != null) {
20354                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20355                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20356                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20357                        .setPackage(launcherComponent.getPackageName());
20358                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20359            }
20360        }
20361    }
20362
20363    /**
20364     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20365     * then reports the most likely home activity or null if there are more than one.
20366     */
20367    private ComponentName getDefaultHomeActivity(int userId) {
20368        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20369        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20370        if (cn != null) {
20371            return cn;
20372        }
20373
20374        // Find the launcher with the highest priority and return that component if there are no
20375        // other home activity with the same priority.
20376        int lastPriority = Integer.MIN_VALUE;
20377        ComponentName lastComponent = null;
20378        final int size = allHomeCandidates.size();
20379        for (int i = 0; i < size; i++) {
20380            final ResolveInfo ri = allHomeCandidates.get(i);
20381            if (ri.priority > lastPriority) {
20382                lastComponent = ri.activityInfo.getComponentName();
20383                lastPriority = ri.priority;
20384            } else if (ri.priority == lastPriority) {
20385                // Two components found with same priority.
20386                lastComponent = null;
20387            }
20388        }
20389        return lastComponent;
20390    }
20391
20392    private Intent getHomeIntent() {
20393        Intent intent = new Intent(Intent.ACTION_MAIN);
20394        intent.addCategory(Intent.CATEGORY_HOME);
20395        intent.addCategory(Intent.CATEGORY_DEFAULT);
20396        return intent;
20397    }
20398
20399    private IntentFilter getHomeFilter() {
20400        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20401        filter.addCategory(Intent.CATEGORY_HOME);
20402        filter.addCategory(Intent.CATEGORY_DEFAULT);
20403        return filter;
20404    }
20405
20406    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20407            int userId) {
20408        Intent intent  = getHomeIntent();
20409        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20410                PackageManager.GET_META_DATA, userId);
20411        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20412                true, false, false, userId);
20413
20414        allHomeCandidates.clear();
20415        if (list != null) {
20416            for (ResolveInfo ri : list) {
20417                allHomeCandidates.add(ri);
20418            }
20419        }
20420        return (preferred == null || preferred.activityInfo == null)
20421                ? null
20422                : new ComponentName(preferred.activityInfo.packageName,
20423                        preferred.activityInfo.name);
20424    }
20425
20426    @Override
20427    public void setHomeActivity(ComponentName comp, int userId) {
20428        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20429            return;
20430        }
20431        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20432        getHomeActivitiesAsUser(homeActivities, userId);
20433
20434        boolean found = false;
20435
20436        final int size = homeActivities.size();
20437        final ComponentName[] set = new ComponentName[size];
20438        for (int i = 0; i < size; i++) {
20439            final ResolveInfo candidate = homeActivities.get(i);
20440            final ActivityInfo info = candidate.activityInfo;
20441            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20442            set[i] = activityName;
20443            if (!found && activityName.equals(comp)) {
20444                found = true;
20445            }
20446        }
20447        if (!found) {
20448            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20449                    + userId);
20450        }
20451        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20452                set, comp, userId);
20453    }
20454
20455    private @Nullable String getSetupWizardPackageName() {
20456        final Intent intent = new Intent(Intent.ACTION_MAIN);
20457        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20458
20459        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20460                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20461                        | MATCH_DISABLED_COMPONENTS,
20462                UserHandle.myUserId());
20463        if (matches.size() == 1) {
20464            return matches.get(0).getComponentInfo().packageName;
20465        } else {
20466            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20467                    + ": matches=" + matches);
20468            return null;
20469        }
20470    }
20471
20472    private @Nullable String getStorageManagerPackageName() {
20473        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20474
20475        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20476                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20477                        | MATCH_DISABLED_COMPONENTS,
20478                UserHandle.myUserId());
20479        if (matches.size() == 1) {
20480            return matches.get(0).getComponentInfo().packageName;
20481        } else {
20482            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20483                    + matches.size() + ": matches=" + matches);
20484            return null;
20485        }
20486    }
20487
20488    @Override
20489    public String getSystemTextClassifierPackageName() {
20490        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20491    }
20492
20493    @Override
20494    public void setApplicationEnabledSetting(String appPackageName,
20495            int newState, int flags, int userId, String callingPackage) {
20496        if (!sUserManager.exists(userId)) return;
20497        if (callingPackage == null) {
20498            callingPackage = Integer.toString(Binder.getCallingUid());
20499        }
20500        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20501    }
20502
20503    @Override
20504    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20505        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20506        synchronized (mPackages) {
20507            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20508            if (pkgSetting != null) {
20509                pkgSetting.setUpdateAvailable(updateAvailable);
20510            }
20511        }
20512    }
20513
20514    @Override
20515    public void setComponentEnabledSetting(ComponentName componentName,
20516            int newState, int flags, int userId) {
20517        if (!sUserManager.exists(userId)) return;
20518        setEnabledSetting(componentName.getPackageName(),
20519                componentName.getClassName(), newState, flags, userId, null);
20520    }
20521
20522    private void setEnabledSetting(final String packageName, String className, int newState,
20523            final int flags, int userId, String callingPackage) {
20524        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20525              || newState == COMPONENT_ENABLED_STATE_ENABLED
20526              || newState == COMPONENT_ENABLED_STATE_DISABLED
20527              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20528              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20529            throw new IllegalArgumentException("Invalid new component state: "
20530                    + newState);
20531        }
20532        PackageSetting pkgSetting;
20533        final int callingUid = Binder.getCallingUid();
20534        final int permission;
20535        if (callingUid == Process.SYSTEM_UID) {
20536            permission = PackageManager.PERMISSION_GRANTED;
20537        } else {
20538            permission = mContext.checkCallingOrSelfPermission(
20539                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20540        }
20541        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20542                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20543        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20544        boolean sendNow = false;
20545        boolean isApp = (className == null);
20546        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20547        String componentName = isApp ? packageName : className;
20548        int packageUid = -1;
20549        ArrayList<String> components;
20550
20551        // reader
20552        synchronized (mPackages) {
20553            pkgSetting = mSettings.mPackages.get(packageName);
20554            if (pkgSetting == null) {
20555                if (!isCallerInstantApp) {
20556                    if (className == null) {
20557                        throw new IllegalArgumentException("Unknown package: " + packageName);
20558                    }
20559                    throw new IllegalArgumentException(
20560                            "Unknown component: " + packageName + "/" + className);
20561                } else {
20562                    // throw SecurityException to prevent leaking package information
20563                    throw new SecurityException(
20564                            "Attempt to change component state; "
20565                            + "pid=" + Binder.getCallingPid()
20566                            + ", uid=" + callingUid
20567                            + (className == null
20568                                    ? ", package=" + packageName
20569                                    : ", component=" + packageName + "/" + className));
20570                }
20571            }
20572        }
20573
20574        // Limit who can change which apps
20575        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20576            // Don't allow apps that don't have permission to modify other apps
20577            if (!allowedByPermission
20578                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20579                throw new SecurityException(
20580                        "Attempt to change component state; "
20581                        + "pid=" + Binder.getCallingPid()
20582                        + ", uid=" + callingUid
20583                        + (className == null
20584                                ? ", package=" + packageName
20585                                : ", component=" + packageName + "/" + className));
20586            }
20587            // Don't allow changing protected packages.
20588            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20589                throw new SecurityException("Cannot disable a protected package: " + packageName);
20590            }
20591        }
20592
20593        synchronized (mPackages) {
20594            if (callingUid == Process.SHELL_UID
20595                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20596                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20597                // unless it is a test package.
20598                int oldState = pkgSetting.getEnabled(userId);
20599                if (className == null
20600                        &&
20601                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20602                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20603                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20604                        &&
20605                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20606                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20607                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20608                    // ok
20609                } else {
20610                    throw new SecurityException(
20611                            "Shell cannot change component state for " + packageName + "/"
20612                                    + className + " to " + newState);
20613                }
20614            }
20615        }
20616        if (className == null) {
20617            // We're dealing with an application/package level state change
20618            synchronized (mPackages) {
20619                if (pkgSetting.getEnabled(userId) == newState) {
20620                    // Nothing to do
20621                    return;
20622                }
20623            }
20624            // If we're enabling a system stub, there's a little more work to do.
20625            // Prior to enabling the package, we need to decompress the APK(s) to the
20626            // data partition and then replace the version on the system partition.
20627            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20628            final boolean isSystemStub = deletedPkg.isStub
20629                    && deletedPkg.isSystem();
20630            if (isSystemStub
20631                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20632                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20633                final File codePath = decompressPackage(deletedPkg);
20634                if (codePath == null) {
20635                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20636                    return;
20637                }
20638                // TODO remove direct parsing of the package object during internal cleanup
20639                // of scan package
20640                // We need to call parse directly here for no other reason than we need
20641                // the new package in order to disable the old one [we use the information
20642                // for some internal optimization to optionally create a new package setting
20643                // object on replace]. However, we can't get the package from the scan
20644                // because the scan modifies live structures and we need to remove the
20645                // old [system] package from the system before a scan can be attempted.
20646                // Once scan is indempotent we can remove this parse and use the package
20647                // object we scanned, prior to adding it to package settings.
20648                final PackageParser pp = new PackageParser();
20649                pp.setSeparateProcesses(mSeparateProcesses);
20650                pp.setDisplayMetrics(mMetrics);
20651                pp.setCallback(mPackageParserCallback);
20652                final PackageParser.Package tmpPkg;
20653                try {
20654                    final @ParseFlags int parseFlags = mDefParseFlags
20655                            | PackageParser.PARSE_MUST_BE_APK
20656                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20657                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20658                } catch (PackageParserException e) {
20659                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20660                    return;
20661                }
20662                synchronized (mInstallLock) {
20663                    // Disable the stub and remove any package entries
20664                    removePackageLI(deletedPkg, true);
20665                    synchronized (mPackages) {
20666                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20667                    }
20668                    final PackageParser.Package pkg;
20669                    try (PackageFreezer freezer =
20670                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20671                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20672                                | PackageParser.PARSE_ENFORCE_CODE;
20673                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20674                                0 /*currentTime*/, null /*user*/);
20675                        prepareAppDataAfterInstallLIF(pkg);
20676                        synchronized (mPackages) {
20677                            try {
20678                                updateSharedLibrariesLPr(pkg, null);
20679                            } catch (PackageManagerException e) {
20680                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20681                            }
20682                            mPermissionManager.updatePermissions(
20683                                    pkg.packageName, pkg, true, mPackages.values(),
20684                                    mPermissionCallback);
20685                            mSettings.writeLPr();
20686                        }
20687                    } catch (PackageManagerException e) {
20688                        // Whoops! Something went wrong; try to roll back to the stub
20689                        Slog.w(TAG, "Failed to install compressed system package:"
20690                                + pkgSetting.name, e);
20691                        // Remove the failed install
20692                        removeCodePathLI(codePath);
20693
20694                        // Install the system package
20695                        try (PackageFreezer freezer =
20696                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20697                            synchronized (mPackages) {
20698                                // NOTE: The system package always needs to be enabled; even
20699                                // if it's for a compressed stub. If we don't, installing the
20700                                // system package fails during scan [scanning checks the disabled
20701                                // packages]. We will reverse this later, after we've "installed"
20702                                // the stub.
20703                                // This leaves us in a fragile state; the stub should never be
20704                                // enabled, so, cross your fingers and hope nothing goes wrong
20705                                // until we can disable the package later.
20706                                enableSystemPackageLPw(deletedPkg);
20707                            }
20708                            installPackageFromSystemLIF(deletedPkg.codePath,
20709                                    false /*isPrivileged*/, null /*allUserHandles*/,
20710                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20711                                    true /*writeSettings*/);
20712                        } catch (PackageManagerException pme) {
20713                            Slog.w(TAG, "Failed to restore system package:"
20714                                    + deletedPkg.packageName, pme);
20715                        } finally {
20716                            synchronized (mPackages) {
20717                                mSettings.disableSystemPackageLPw(
20718                                        deletedPkg.packageName, true /*replaced*/);
20719                                mSettings.writeLPr();
20720                            }
20721                        }
20722                        return;
20723                    }
20724                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20725                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20726                    mDexManager.notifyPackageUpdated(pkg.packageName,
20727                            pkg.baseCodePath, pkg.splitCodePaths);
20728                }
20729            }
20730            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20731                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20732                // Don't care about who enables an app.
20733                callingPackage = null;
20734            }
20735            synchronized (mPackages) {
20736                pkgSetting.setEnabled(newState, userId, callingPackage);
20737            }
20738        } else {
20739            synchronized (mPackages) {
20740                // We're dealing with a component level state change
20741                // First, verify that this is a valid class name.
20742                PackageParser.Package pkg = pkgSetting.pkg;
20743                if (pkg == null || !pkg.hasComponentClassName(className)) {
20744                    if (pkg != null &&
20745                            pkg.applicationInfo.targetSdkVersion >=
20746                                    Build.VERSION_CODES.JELLY_BEAN) {
20747                        throw new IllegalArgumentException("Component class " + className
20748                                + " does not exist in " + packageName);
20749                    } else {
20750                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20751                                + className + " does not exist in " + packageName);
20752                    }
20753                }
20754                switch (newState) {
20755                    case COMPONENT_ENABLED_STATE_ENABLED:
20756                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20757                            return;
20758                        }
20759                        break;
20760                    case COMPONENT_ENABLED_STATE_DISABLED:
20761                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20762                            return;
20763                        }
20764                        break;
20765                    case COMPONENT_ENABLED_STATE_DEFAULT:
20766                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20767                            return;
20768                        }
20769                        break;
20770                    default:
20771                        Slog.e(TAG, "Invalid new component state: " + newState);
20772                        return;
20773                }
20774            }
20775        }
20776        synchronized (mPackages) {
20777            scheduleWritePackageRestrictionsLocked(userId);
20778            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20779            final long callingId = Binder.clearCallingIdentity();
20780            try {
20781                updateInstantAppInstallerLocked(packageName);
20782            } finally {
20783                Binder.restoreCallingIdentity(callingId);
20784            }
20785            components = mPendingBroadcasts.get(userId, packageName);
20786            final boolean newPackage = components == null;
20787            if (newPackage) {
20788                components = new ArrayList<String>();
20789            }
20790            if (!components.contains(componentName)) {
20791                components.add(componentName);
20792            }
20793            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20794                sendNow = true;
20795                // Purge entry from pending broadcast list if another one exists already
20796                // since we are sending one right away.
20797                mPendingBroadcasts.remove(userId, packageName);
20798            } else {
20799                if (newPackage) {
20800                    mPendingBroadcasts.put(userId, packageName, components);
20801                }
20802                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20803                    // Schedule a message
20804                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20805                }
20806            }
20807        }
20808
20809        long callingId = Binder.clearCallingIdentity();
20810        try {
20811            if (sendNow) {
20812                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20813                sendPackageChangedBroadcast(packageName,
20814                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20815            }
20816        } finally {
20817            Binder.restoreCallingIdentity(callingId);
20818        }
20819    }
20820
20821    @Override
20822    public void flushPackageRestrictionsAsUser(int userId) {
20823        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20824            return;
20825        }
20826        if (!sUserManager.exists(userId)) {
20827            return;
20828        }
20829        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20830                false /* checkShell */, "flushPackageRestrictions");
20831        synchronized (mPackages) {
20832            mSettings.writePackageRestrictionsLPr(userId);
20833            mDirtyUsers.remove(userId);
20834            if (mDirtyUsers.isEmpty()) {
20835                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20836            }
20837        }
20838    }
20839
20840    private void sendPackageChangedBroadcast(String packageName,
20841            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20842        if (DEBUG_INSTALL)
20843            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20844                    + componentNames);
20845        Bundle extras = new Bundle(4);
20846        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20847        String nameList[] = new String[componentNames.size()];
20848        componentNames.toArray(nameList);
20849        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20850        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20851        extras.putInt(Intent.EXTRA_UID, packageUid);
20852        // If this is not reporting a change of the overall package, then only send it
20853        // to registered receivers.  We don't want to launch a swath of apps for every
20854        // little component state change.
20855        final int flags = !componentNames.contains(packageName)
20856                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20857        final int userId = UserHandle.getUserId(packageUid);
20858        final boolean isInstantApp = isInstantApp(packageName, userId);
20859        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20860        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20861        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20862                userIds, instantUserIds);
20863    }
20864
20865    @Override
20866    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20867        if (!sUserManager.exists(userId)) return;
20868        final int callingUid = Binder.getCallingUid();
20869        if (getInstantAppPackageName(callingUid) != null) {
20870            return;
20871        }
20872        final int permission = mContext.checkCallingOrSelfPermission(
20873                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20874        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20875        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20876                true /* requireFullPermission */, true /* checkShell */, "stop package");
20877        // writer
20878        synchronized (mPackages) {
20879            final PackageSetting ps = mSettings.mPackages.get(packageName);
20880            if (!filterAppAccessLPr(ps, callingUid, userId)
20881                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20882                            allowedByPermission, callingUid, userId)) {
20883                scheduleWritePackageRestrictionsLocked(userId);
20884            }
20885        }
20886    }
20887
20888    @Override
20889    public String getInstallerPackageName(String packageName) {
20890        final int callingUid = Binder.getCallingUid();
20891        synchronized (mPackages) {
20892            final PackageSetting ps = mSettings.mPackages.get(packageName);
20893            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20894                return null;
20895            }
20896            return mSettings.getInstallerPackageNameLPr(packageName);
20897        }
20898    }
20899
20900    public boolean isOrphaned(String packageName) {
20901        // reader
20902        synchronized (mPackages) {
20903            return mSettings.isOrphaned(packageName);
20904        }
20905    }
20906
20907    @Override
20908    public int getApplicationEnabledSetting(String packageName, int userId) {
20909        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20910        int callingUid = Binder.getCallingUid();
20911        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20912                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20913        // reader
20914        synchronized (mPackages) {
20915            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20916                return COMPONENT_ENABLED_STATE_DISABLED;
20917            }
20918            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20919        }
20920    }
20921
20922    @Override
20923    public int getComponentEnabledSetting(ComponentName component, int userId) {
20924        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20925        int callingUid = Binder.getCallingUid();
20926        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20927                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20928        synchronized (mPackages) {
20929            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20930                    component, TYPE_UNKNOWN, userId)) {
20931                return COMPONENT_ENABLED_STATE_DISABLED;
20932            }
20933            return mSettings.getComponentEnabledSettingLPr(component, userId);
20934        }
20935    }
20936
20937    @Override
20938    public void enterSafeMode() {
20939        enforceSystemOrRoot("Only the system can request entering safe mode");
20940
20941        if (!mSystemReady) {
20942            mSafeMode = true;
20943        }
20944    }
20945
20946    @Override
20947    public void systemReady() {
20948        enforceSystemOrRoot("Only the system can claim the system is ready");
20949
20950        mSystemReady = true;
20951        final ContentResolver resolver = mContext.getContentResolver();
20952        ContentObserver co = new ContentObserver(mHandler) {
20953            @Override
20954            public void onChange(boolean selfChange) {
20955                mWebInstantAppsDisabled =
20956                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20957                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20958            }
20959        };
20960        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20961                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20962                false, co, UserHandle.USER_SYSTEM);
20963        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20964                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20965        co.onChange(true);
20966
20967        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20968        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20969        // it is done.
20970        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20971            @Override
20972            public void onChange(boolean selfChange) {
20973                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20974                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20975                        oobEnabled == 1 ? "true" : "false");
20976            }
20977        };
20978        mContext.getContentResolver().registerContentObserver(
20979                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20980                UserHandle.USER_SYSTEM);
20981        // At boot, restore the value from the setting, which persists across reboot.
20982        privAppOobObserver.onChange(true);
20983
20984        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20985        // disabled after already being started.
20986        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20987                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20988
20989        // Read the compatibilty setting when the system is ready.
20990        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20991                mContext.getContentResolver(),
20992                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20993        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20994        if (DEBUG_SETTINGS) {
20995            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20996        }
20997
20998        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20999
21000        synchronized (mPackages) {
21001            // Verify that all of the preferred activity components actually
21002            // exist.  It is possible for applications to be updated and at
21003            // that point remove a previously declared activity component that
21004            // had been set as a preferred activity.  We try to clean this up
21005            // the next time we encounter that preferred activity, but it is
21006            // possible for the user flow to never be able to return to that
21007            // situation so here we do a sanity check to make sure we haven't
21008            // left any junk around.
21009            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21010            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21011                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21012                removed.clear();
21013                for (PreferredActivity pa : pir.filterSet()) {
21014                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21015                        removed.add(pa);
21016                    }
21017                }
21018                if (removed.size() > 0) {
21019                    for (int r=0; r<removed.size(); r++) {
21020                        PreferredActivity pa = removed.get(r);
21021                        Slog.w(TAG, "Removing dangling preferred activity: "
21022                                + pa.mPref.mComponent);
21023                        pir.removeFilter(pa);
21024                    }
21025                    mSettings.writePackageRestrictionsLPr(
21026                            mSettings.mPreferredActivities.keyAt(i));
21027                }
21028            }
21029
21030            for (int userId : UserManagerService.getInstance().getUserIds()) {
21031                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21032                    grantPermissionsUserIds = ArrayUtils.appendInt(
21033                            grantPermissionsUserIds, userId);
21034                }
21035            }
21036        }
21037        sUserManager.systemReady();
21038        // If we upgraded grant all default permissions before kicking off.
21039        for (int userId : grantPermissionsUserIds) {
21040            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21041        }
21042
21043        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21044            // If we did not grant default permissions, we preload from this the
21045            // default permission exceptions lazily to ensure we don't hit the
21046            // disk on a new user creation.
21047            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21048        }
21049
21050        // Now that we've scanned all packages, and granted any default
21051        // permissions, ensure permissions are updated. Beware of dragons if you
21052        // try optimizing this.
21053        synchronized (mPackages) {
21054            mPermissionManager.updateAllPermissions(
21055                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21056                    mPermissionCallback);
21057        }
21058
21059        // Kick off any messages waiting for system ready
21060        if (mPostSystemReadyMessages != null) {
21061            for (Message msg : mPostSystemReadyMessages) {
21062                msg.sendToTarget();
21063            }
21064            mPostSystemReadyMessages = null;
21065        }
21066
21067        // Watch for external volumes that come and go over time
21068        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21069        storage.registerListener(mStorageListener);
21070
21071        mInstallerService.systemReady();
21072        mPackageDexOptimizer.systemReady();
21073
21074        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21075                StorageManagerInternal.class);
21076        StorageManagerInternal.addExternalStoragePolicy(
21077                new StorageManagerInternal.ExternalStorageMountPolicy() {
21078            @Override
21079            public int getMountMode(int uid, String packageName) {
21080                if (Process.isIsolated(uid)) {
21081                    return Zygote.MOUNT_EXTERNAL_NONE;
21082                }
21083                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21084                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21085                }
21086                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21087                    return Zygote.MOUNT_EXTERNAL_READ;
21088                }
21089                return Zygote.MOUNT_EXTERNAL_WRITE;
21090            }
21091
21092            @Override
21093            public boolean hasExternalStorage(int uid, String packageName) {
21094                return true;
21095            }
21096        });
21097
21098        // Now that we're mostly running, clean up stale users and apps
21099        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21100        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21101
21102        mPermissionManager.systemReady();
21103
21104        if (mInstantAppResolverConnection != null) {
21105            mContext.registerReceiver(new BroadcastReceiver() {
21106                @Override
21107                public void onReceive(Context context, Intent intent) {
21108                    mInstantAppResolverConnection.optimisticBind();
21109                    mContext.unregisterReceiver(this);
21110                }
21111            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21112        }
21113    }
21114
21115    public void waitForAppDataPrepared() {
21116        if (mPrepareAppDataFuture == null) {
21117            return;
21118        }
21119        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21120        mPrepareAppDataFuture = null;
21121    }
21122
21123    @Override
21124    public boolean isSafeMode() {
21125        // allow instant applications
21126        return mSafeMode;
21127    }
21128
21129    @Override
21130    public boolean hasSystemUidErrors() {
21131        // allow instant applications
21132        return mHasSystemUidErrors;
21133    }
21134
21135    static String arrayToString(int[] array) {
21136        StringBuffer buf = new StringBuffer(128);
21137        buf.append('[');
21138        if (array != null) {
21139            for (int i=0; i<array.length; i++) {
21140                if (i > 0) buf.append(", ");
21141                buf.append(array[i]);
21142            }
21143        }
21144        buf.append(']');
21145        return buf.toString();
21146    }
21147
21148    @Override
21149    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21150            FileDescriptor err, String[] args, ShellCallback callback,
21151            ResultReceiver resultReceiver) {
21152        (new PackageManagerShellCommand(this)).exec(
21153                this, in, out, err, args, callback, resultReceiver);
21154    }
21155
21156    @Override
21157    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21158        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21159
21160        DumpState dumpState = new DumpState();
21161        boolean fullPreferred = false;
21162        boolean checkin = false;
21163
21164        String packageName = null;
21165        ArraySet<String> permissionNames = null;
21166
21167        int opti = 0;
21168        while (opti < args.length) {
21169            String opt = args[opti];
21170            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21171                break;
21172            }
21173            opti++;
21174
21175            if ("-a".equals(opt)) {
21176                // Right now we only know how to print all.
21177            } else if ("-h".equals(opt)) {
21178                pw.println("Package manager dump options:");
21179                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21180                pw.println("    --checkin: dump for a checkin");
21181                pw.println("    -f: print details of intent filters");
21182                pw.println("    -h: print this help");
21183                pw.println("  cmd may be one of:");
21184                pw.println("    l[ibraries]: list known shared libraries");
21185                pw.println("    f[eatures]: list device features");
21186                pw.println("    k[eysets]: print known keysets");
21187                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21188                pw.println("    perm[issions]: dump permissions");
21189                pw.println("    permission [name ...]: dump declaration and use of given permission");
21190                pw.println("    pref[erred]: print preferred package settings");
21191                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21192                pw.println("    prov[iders]: dump content providers");
21193                pw.println("    p[ackages]: dump installed packages");
21194                pw.println("    s[hared-users]: dump shared user IDs");
21195                pw.println("    m[essages]: print collected runtime messages");
21196                pw.println("    v[erifiers]: print package verifier info");
21197                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21198                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21199                pw.println("    version: print database version info");
21200                pw.println("    write: write current settings now");
21201                pw.println("    installs: details about install sessions");
21202                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21203                pw.println("    dexopt: dump dexopt state");
21204                pw.println("    compiler-stats: dump compiler statistics");
21205                pw.println("    service-permissions: dump permissions required by services");
21206                pw.println("    <package.name>: info about given package");
21207                return;
21208            } else if ("--checkin".equals(opt)) {
21209                checkin = true;
21210            } else if ("-f".equals(opt)) {
21211                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21212            } else if ("--proto".equals(opt)) {
21213                dumpProto(fd);
21214                return;
21215            } else {
21216                pw.println("Unknown argument: " + opt + "; use -h for help");
21217            }
21218        }
21219
21220        // Is the caller requesting to dump a particular piece of data?
21221        if (opti < args.length) {
21222            String cmd = args[opti];
21223            opti++;
21224            // Is this a package name?
21225            if ("android".equals(cmd) || cmd.contains(".")) {
21226                packageName = cmd;
21227                // When dumping a single package, we always dump all of its
21228                // filter information since the amount of data will be reasonable.
21229                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21230            } else if ("check-permission".equals(cmd)) {
21231                if (opti >= args.length) {
21232                    pw.println("Error: check-permission missing permission argument");
21233                    return;
21234                }
21235                String perm = args[opti];
21236                opti++;
21237                if (opti >= args.length) {
21238                    pw.println("Error: check-permission missing package argument");
21239                    return;
21240                }
21241
21242                String pkg = args[opti];
21243                opti++;
21244                int user = UserHandle.getUserId(Binder.getCallingUid());
21245                if (opti < args.length) {
21246                    try {
21247                        user = Integer.parseInt(args[opti]);
21248                    } catch (NumberFormatException e) {
21249                        pw.println("Error: check-permission user argument is not a number: "
21250                                + args[opti]);
21251                        return;
21252                    }
21253                }
21254
21255                // Normalize package name to handle renamed packages and static libs
21256                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21257
21258                pw.println(checkPermission(perm, pkg, user));
21259                return;
21260            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21261                dumpState.setDump(DumpState.DUMP_LIBS);
21262            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21263                dumpState.setDump(DumpState.DUMP_FEATURES);
21264            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21265                if (opti >= args.length) {
21266                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21267                            | DumpState.DUMP_SERVICE_RESOLVERS
21268                            | DumpState.DUMP_RECEIVER_RESOLVERS
21269                            | DumpState.DUMP_CONTENT_RESOLVERS);
21270                } else {
21271                    while (opti < args.length) {
21272                        String name = args[opti];
21273                        if ("a".equals(name) || "activity".equals(name)) {
21274                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21275                        } else if ("s".equals(name) || "service".equals(name)) {
21276                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21277                        } else if ("r".equals(name) || "receiver".equals(name)) {
21278                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21279                        } else if ("c".equals(name) || "content".equals(name)) {
21280                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21281                        } else {
21282                            pw.println("Error: unknown resolver table type: " + name);
21283                            return;
21284                        }
21285                        opti++;
21286                    }
21287                }
21288            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21289                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21290            } else if ("permission".equals(cmd)) {
21291                if (opti >= args.length) {
21292                    pw.println("Error: permission requires permission name");
21293                    return;
21294                }
21295                permissionNames = new ArraySet<>();
21296                while (opti < args.length) {
21297                    permissionNames.add(args[opti]);
21298                    opti++;
21299                }
21300                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21301                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21302            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21303                dumpState.setDump(DumpState.DUMP_PREFERRED);
21304            } else if ("preferred-xml".equals(cmd)) {
21305                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21306                if (opti < args.length && "--full".equals(args[opti])) {
21307                    fullPreferred = true;
21308                    opti++;
21309                }
21310            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21311                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21312            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21313                dumpState.setDump(DumpState.DUMP_PACKAGES);
21314            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21315                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21316            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21317                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21318            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21319                dumpState.setDump(DumpState.DUMP_MESSAGES);
21320            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21321                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21322            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21323                    || "intent-filter-verifiers".equals(cmd)) {
21324                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21325            } else if ("version".equals(cmd)) {
21326                dumpState.setDump(DumpState.DUMP_VERSION);
21327            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21328                dumpState.setDump(DumpState.DUMP_KEYSETS);
21329            } else if ("installs".equals(cmd)) {
21330                dumpState.setDump(DumpState.DUMP_INSTALLS);
21331            } else if ("frozen".equals(cmd)) {
21332                dumpState.setDump(DumpState.DUMP_FROZEN);
21333            } else if ("volumes".equals(cmd)) {
21334                dumpState.setDump(DumpState.DUMP_VOLUMES);
21335            } else if ("dexopt".equals(cmd)) {
21336                dumpState.setDump(DumpState.DUMP_DEXOPT);
21337            } else if ("compiler-stats".equals(cmd)) {
21338                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21339            } else if ("changes".equals(cmd)) {
21340                dumpState.setDump(DumpState.DUMP_CHANGES);
21341            } else if ("service-permissions".equals(cmd)) {
21342                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21343            } else if ("write".equals(cmd)) {
21344                synchronized (mPackages) {
21345                    mSettings.writeLPr();
21346                    pw.println("Settings written.");
21347                    return;
21348                }
21349            }
21350        }
21351
21352        if (checkin) {
21353            pw.println("vers,1");
21354        }
21355
21356        // reader
21357        synchronized (mPackages) {
21358            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21359                if (!checkin) {
21360                    if (dumpState.onTitlePrinted())
21361                        pw.println();
21362                    pw.println("Database versions:");
21363                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21364                }
21365            }
21366
21367            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21368                if (!checkin) {
21369                    if (dumpState.onTitlePrinted())
21370                        pw.println();
21371                    pw.println("Verifiers:");
21372                    pw.print("  Required: ");
21373                    pw.print(mRequiredVerifierPackage);
21374                    pw.print(" (uid=");
21375                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21376                            UserHandle.USER_SYSTEM));
21377                    pw.println(")");
21378                } else if (mRequiredVerifierPackage != null) {
21379                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21380                    pw.print(",");
21381                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21382                            UserHandle.USER_SYSTEM));
21383                }
21384            }
21385
21386            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21387                    packageName == null) {
21388                if (mIntentFilterVerifierComponent != null) {
21389                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21390                    if (!checkin) {
21391                        if (dumpState.onTitlePrinted())
21392                            pw.println();
21393                        pw.println("Intent Filter Verifier:");
21394                        pw.print("  Using: ");
21395                        pw.print(verifierPackageName);
21396                        pw.print(" (uid=");
21397                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21398                                UserHandle.USER_SYSTEM));
21399                        pw.println(")");
21400                    } else if (verifierPackageName != null) {
21401                        pw.print("ifv,"); pw.print(verifierPackageName);
21402                        pw.print(",");
21403                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21404                                UserHandle.USER_SYSTEM));
21405                    }
21406                } else {
21407                    pw.println();
21408                    pw.println("No Intent Filter Verifier available!");
21409                }
21410            }
21411
21412            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21413                boolean printedHeader = false;
21414                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21415                while (it.hasNext()) {
21416                    String libName = it.next();
21417                    LongSparseArray<SharedLibraryEntry> versionedLib
21418                            = mSharedLibraries.get(libName);
21419                    if (versionedLib == null) {
21420                        continue;
21421                    }
21422                    final int versionCount = versionedLib.size();
21423                    for (int i = 0; i < versionCount; i++) {
21424                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21425                        if (!checkin) {
21426                            if (!printedHeader) {
21427                                if (dumpState.onTitlePrinted())
21428                                    pw.println();
21429                                pw.println("Libraries:");
21430                                printedHeader = true;
21431                            }
21432                            pw.print("  ");
21433                        } else {
21434                            pw.print("lib,");
21435                        }
21436                        pw.print(libEntry.info.getName());
21437                        if (libEntry.info.isStatic()) {
21438                            pw.print(" version=" + libEntry.info.getLongVersion());
21439                        }
21440                        if (!checkin) {
21441                            pw.print(" -> ");
21442                        }
21443                        if (libEntry.path != null) {
21444                            pw.print(" (jar) ");
21445                            pw.print(libEntry.path);
21446                        } else {
21447                            pw.print(" (apk) ");
21448                            pw.print(libEntry.apk);
21449                        }
21450                        pw.println();
21451                    }
21452                }
21453            }
21454
21455            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21456                if (dumpState.onTitlePrinted())
21457                    pw.println();
21458                if (!checkin) {
21459                    pw.println("Features:");
21460                }
21461
21462                synchronized (mAvailableFeatures) {
21463                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21464                        if (checkin) {
21465                            pw.print("feat,");
21466                            pw.print(feat.name);
21467                            pw.print(",");
21468                            pw.println(feat.version);
21469                        } else {
21470                            pw.print("  ");
21471                            pw.print(feat.name);
21472                            if (feat.version > 0) {
21473                                pw.print(" version=");
21474                                pw.print(feat.version);
21475                            }
21476                            pw.println();
21477                        }
21478                    }
21479                }
21480            }
21481
21482            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21483                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21484                        : "Activity Resolver Table:", "  ", packageName,
21485                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21486                    dumpState.setTitlePrinted(true);
21487                }
21488            }
21489            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21490                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21491                        : "Receiver Resolver Table:", "  ", packageName,
21492                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21493                    dumpState.setTitlePrinted(true);
21494                }
21495            }
21496            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21497                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21498                        : "Service Resolver Table:", "  ", packageName,
21499                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21500                    dumpState.setTitlePrinted(true);
21501                }
21502            }
21503            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21504                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21505                        : "Provider Resolver Table:", "  ", packageName,
21506                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21507                    dumpState.setTitlePrinted(true);
21508                }
21509            }
21510
21511            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21512                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21513                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21514                    int user = mSettings.mPreferredActivities.keyAt(i);
21515                    if (pir.dump(pw,
21516                            dumpState.getTitlePrinted()
21517                                ? "\nPreferred Activities User " + user + ":"
21518                                : "Preferred Activities User " + user + ":", "  ",
21519                            packageName, true, false)) {
21520                        dumpState.setTitlePrinted(true);
21521                    }
21522                }
21523            }
21524
21525            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21526                pw.flush();
21527                FileOutputStream fout = new FileOutputStream(fd);
21528                BufferedOutputStream str = new BufferedOutputStream(fout);
21529                XmlSerializer serializer = new FastXmlSerializer();
21530                try {
21531                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21532                    serializer.startDocument(null, true);
21533                    serializer.setFeature(
21534                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21535                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21536                    serializer.endDocument();
21537                    serializer.flush();
21538                } catch (IllegalArgumentException e) {
21539                    pw.println("Failed writing: " + e);
21540                } catch (IllegalStateException e) {
21541                    pw.println("Failed writing: " + e);
21542                } catch (IOException e) {
21543                    pw.println("Failed writing: " + e);
21544                }
21545            }
21546
21547            if (!checkin
21548                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21549                    && packageName == null) {
21550                pw.println();
21551                int count = mSettings.mPackages.size();
21552                if (count == 0) {
21553                    pw.println("No applications!");
21554                    pw.println();
21555                } else {
21556                    final String prefix = "  ";
21557                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21558                    if (allPackageSettings.size() == 0) {
21559                        pw.println("No domain preferred apps!");
21560                        pw.println();
21561                    } else {
21562                        pw.println("App verification status:");
21563                        pw.println();
21564                        count = 0;
21565                        for (PackageSetting ps : allPackageSettings) {
21566                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21567                            if (ivi == null || ivi.getPackageName() == null) continue;
21568                            pw.println(prefix + "Package: " + ivi.getPackageName());
21569                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21570                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21571                            pw.println();
21572                            count++;
21573                        }
21574                        if (count == 0) {
21575                            pw.println(prefix + "No app verification established.");
21576                            pw.println();
21577                        }
21578                        for (int userId : sUserManager.getUserIds()) {
21579                            pw.println("App linkages for user " + userId + ":");
21580                            pw.println();
21581                            count = 0;
21582                            for (PackageSetting ps : allPackageSettings) {
21583                                final long status = ps.getDomainVerificationStatusForUser(userId);
21584                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21585                                        && !DEBUG_DOMAIN_VERIFICATION) {
21586                                    continue;
21587                                }
21588                                pw.println(prefix + "Package: " + ps.name);
21589                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21590                                String statusStr = IntentFilterVerificationInfo.
21591                                        getStatusStringFromValue(status);
21592                                pw.println(prefix + "Status:  " + statusStr);
21593                                pw.println();
21594                                count++;
21595                            }
21596                            if (count == 0) {
21597                                pw.println(prefix + "No configured app linkages.");
21598                                pw.println();
21599                            }
21600                        }
21601                    }
21602                }
21603            }
21604
21605            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21606                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21607            }
21608
21609            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21610                boolean printedSomething = false;
21611                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21612                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21613                        continue;
21614                    }
21615                    if (!printedSomething) {
21616                        if (dumpState.onTitlePrinted())
21617                            pw.println();
21618                        pw.println("Registered ContentProviders:");
21619                        printedSomething = true;
21620                    }
21621                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21622                    pw.print("    "); pw.println(p.toString());
21623                }
21624                printedSomething = false;
21625                for (Map.Entry<String, PackageParser.Provider> entry :
21626                        mProvidersByAuthority.entrySet()) {
21627                    PackageParser.Provider p = entry.getValue();
21628                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21629                        continue;
21630                    }
21631                    if (!printedSomething) {
21632                        if (dumpState.onTitlePrinted())
21633                            pw.println();
21634                        pw.println("ContentProvider Authorities:");
21635                        printedSomething = true;
21636                    }
21637                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21638                    pw.print("    "); pw.println(p.toString());
21639                    if (p.info != null && p.info.applicationInfo != null) {
21640                        final String appInfo = p.info.applicationInfo.toString();
21641                        pw.print("      applicationInfo="); pw.println(appInfo);
21642                    }
21643                }
21644            }
21645
21646            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21647                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21648            }
21649
21650            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21651                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21652            }
21653
21654            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21655                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21656            }
21657
21658            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21659                if (dumpState.onTitlePrinted()) pw.println();
21660                pw.println("Package Changes:");
21661                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21662                final int K = mChangedPackages.size();
21663                for (int i = 0; i < K; i++) {
21664                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21665                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21666                    final int N = changes.size();
21667                    if (N == 0) {
21668                        pw.print("    "); pw.println("No packages changed");
21669                    } else {
21670                        for (int j = 0; j < N; j++) {
21671                            final String pkgName = changes.valueAt(j);
21672                            final int sequenceNumber = changes.keyAt(j);
21673                            pw.print("    ");
21674                            pw.print("seq=");
21675                            pw.print(sequenceNumber);
21676                            pw.print(", package=");
21677                            pw.println(pkgName);
21678                        }
21679                    }
21680                }
21681            }
21682
21683            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21684                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21685            }
21686
21687            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21688                // XXX should handle packageName != null by dumping only install data that
21689                // the given package is involved with.
21690                if (dumpState.onTitlePrinted()) pw.println();
21691
21692                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21693                ipw.println();
21694                ipw.println("Frozen packages:");
21695                ipw.increaseIndent();
21696                if (mFrozenPackages.size() == 0) {
21697                    ipw.println("(none)");
21698                } else {
21699                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21700                        ipw.println(mFrozenPackages.valueAt(i));
21701                    }
21702                }
21703                ipw.decreaseIndent();
21704            }
21705
21706            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21707                if (dumpState.onTitlePrinted()) pw.println();
21708
21709                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21710                ipw.println();
21711                ipw.println("Loaded volumes:");
21712                ipw.increaseIndent();
21713                if (mLoadedVolumes.size() == 0) {
21714                    ipw.println("(none)");
21715                } else {
21716                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21717                        ipw.println(mLoadedVolumes.valueAt(i));
21718                    }
21719                }
21720                ipw.decreaseIndent();
21721            }
21722
21723            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21724                    && packageName == null) {
21725                if (dumpState.onTitlePrinted()) pw.println();
21726                pw.println("Service permissions:");
21727
21728                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21729                while (filterIterator.hasNext()) {
21730                    final ServiceIntentInfo info = filterIterator.next();
21731                    final ServiceInfo serviceInfo = info.service.info;
21732                    final String permission = serviceInfo.permission;
21733                    if (permission != null) {
21734                        pw.print("    ");
21735                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21736                        pw.print(": ");
21737                        pw.println(permission);
21738                    }
21739                }
21740            }
21741
21742            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21743                if (dumpState.onTitlePrinted()) pw.println();
21744                dumpDexoptStateLPr(pw, packageName);
21745            }
21746
21747            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21748                if (dumpState.onTitlePrinted()) pw.println();
21749                dumpCompilerStatsLPr(pw, packageName);
21750            }
21751
21752            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21753                if (dumpState.onTitlePrinted()) pw.println();
21754                mSettings.dumpReadMessagesLPr(pw, dumpState);
21755
21756                pw.println();
21757                pw.println("Package warning messages:");
21758                dumpCriticalInfo(pw, null);
21759            }
21760
21761            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21762                dumpCriticalInfo(pw, "msg,");
21763            }
21764        }
21765
21766        // PackageInstaller should be called outside of mPackages lock
21767        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21768            // XXX should handle packageName != null by dumping only install data that
21769            // the given package is involved with.
21770            if (dumpState.onTitlePrinted()) pw.println();
21771            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21772        }
21773    }
21774
21775    private void dumpProto(FileDescriptor fd) {
21776        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21777
21778        synchronized (mPackages) {
21779            final long requiredVerifierPackageToken =
21780                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21781            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21782            proto.write(
21783                    PackageServiceDumpProto.PackageShortProto.UID,
21784                    getPackageUid(
21785                            mRequiredVerifierPackage,
21786                            MATCH_DEBUG_TRIAGED_MISSING,
21787                            UserHandle.USER_SYSTEM));
21788            proto.end(requiredVerifierPackageToken);
21789
21790            if (mIntentFilterVerifierComponent != null) {
21791                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21792                final long verifierPackageToken =
21793                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21794                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21795                proto.write(
21796                        PackageServiceDumpProto.PackageShortProto.UID,
21797                        getPackageUid(
21798                                verifierPackageName,
21799                                MATCH_DEBUG_TRIAGED_MISSING,
21800                                UserHandle.USER_SYSTEM));
21801                proto.end(verifierPackageToken);
21802            }
21803
21804            dumpSharedLibrariesProto(proto);
21805            dumpFeaturesProto(proto);
21806            mSettings.dumpPackagesProto(proto);
21807            mSettings.dumpSharedUsersProto(proto);
21808            dumpCriticalInfo(proto);
21809        }
21810        proto.flush();
21811    }
21812
21813    private void dumpFeaturesProto(ProtoOutputStream proto) {
21814        synchronized (mAvailableFeatures) {
21815            final int count = mAvailableFeatures.size();
21816            for (int i = 0; i < count; i++) {
21817                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21818            }
21819        }
21820    }
21821
21822    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21823        final int count = mSharedLibraries.size();
21824        for (int i = 0; i < count; i++) {
21825            final String libName = mSharedLibraries.keyAt(i);
21826            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21827            if (versionedLib == null) {
21828                continue;
21829            }
21830            final int versionCount = versionedLib.size();
21831            for (int j = 0; j < versionCount; j++) {
21832                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21833                final long sharedLibraryToken =
21834                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21835                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21836                final boolean isJar = (libEntry.path != null);
21837                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21838                if (isJar) {
21839                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21840                } else {
21841                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21842                }
21843                proto.end(sharedLibraryToken);
21844            }
21845        }
21846    }
21847
21848    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21849        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21850        ipw.println();
21851        ipw.println("Dexopt state:");
21852        ipw.increaseIndent();
21853        Collection<PackageParser.Package> packages = null;
21854        if (packageName != null) {
21855            PackageParser.Package targetPackage = mPackages.get(packageName);
21856            if (targetPackage != null) {
21857                packages = Collections.singletonList(targetPackage);
21858            } else {
21859                ipw.println("Unable to find package: " + packageName);
21860                return;
21861            }
21862        } else {
21863            packages = mPackages.values();
21864        }
21865
21866        for (PackageParser.Package pkg : packages) {
21867            ipw.println("[" + pkg.packageName + "]");
21868            ipw.increaseIndent();
21869            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21870                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21871            ipw.decreaseIndent();
21872        }
21873    }
21874
21875    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21876        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21877        ipw.println();
21878        ipw.println("Compiler stats:");
21879        ipw.increaseIndent();
21880        Collection<PackageParser.Package> packages = null;
21881        if (packageName != null) {
21882            PackageParser.Package targetPackage = mPackages.get(packageName);
21883            if (targetPackage != null) {
21884                packages = Collections.singletonList(targetPackage);
21885            } else {
21886                ipw.println("Unable to find package: " + packageName);
21887                return;
21888            }
21889        } else {
21890            packages = mPackages.values();
21891        }
21892
21893        for (PackageParser.Package pkg : packages) {
21894            ipw.println("[" + pkg.packageName + "]");
21895            ipw.increaseIndent();
21896
21897            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21898            if (stats == null) {
21899                ipw.println("(No recorded stats)");
21900            } else {
21901                stats.dump(ipw);
21902            }
21903            ipw.decreaseIndent();
21904        }
21905    }
21906
21907    private String dumpDomainString(String packageName) {
21908        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21909                .getList();
21910        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21911
21912        ArraySet<String> result = new ArraySet<>();
21913        if (iviList.size() > 0) {
21914            for (IntentFilterVerificationInfo ivi : iviList) {
21915                for (String host : ivi.getDomains()) {
21916                    result.add(host);
21917                }
21918            }
21919        }
21920        if (filters != null && filters.size() > 0) {
21921            for (IntentFilter filter : filters) {
21922                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21923                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21924                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21925                    result.addAll(filter.getHostsList());
21926                }
21927            }
21928        }
21929
21930        StringBuilder sb = new StringBuilder(result.size() * 16);
21931        for (String domain : result) {
21932            if (sb.length() > 0) sb.append(" ");
21933            sb.append(domain);
21934        }
21935        return sb.toString();
21936    }
21937
21938    // ------- apps on sdcard specific code -------
21939    static final boolean DEBUG_SD_INSTALL = false;
21940
21941    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21942
21943    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21944
21945    private boolean mMediaMounted = false;
21946
21947    static String getEncryptKey() {
21948        try {
21949            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21950                    SD_ENCRYPTION_KEYSTORE_NAME);
21951            if (sdEncKey == null) {
21952                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21953                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21954                if (sdEncKey == null) {
21955                    Slog.e(TAG, "Failed to create encryption keys");
21956                    return null;
21957                }
21958            }
21959            return sdEncKey;
21960        } catch (NoSuchAlgorithmException nsae) {
21961            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21962            return null;
21963        } catch (IOException ioe) {
21964            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21965            return null;
21966        }
21967    }
21968
21969    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21970            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21971        final int size = infos.size();
21972        final String[] packageNames = new String[size];
21973        final int[] packageUids = new int[size];
21974        for (int i = 0; i < size; i++) {
21975            final ApplicationInfo info = infos.get(i);
21976            packageNames[i] = info.packageName;
21977            packageUids[i] = info.uid;
21978        }
21979        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21980                finishedReceiver);
21981    }
21982
21983    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21984            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21985        sendResourcesChangedBroadcast(mediaStatus, replacing,
21986                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21987    }
21988
21989    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21990            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21991        int size = pkgList.length;
21992        if (size > 0) {
21993            // Send broadcasts here
21994            Bundle extras = new Bundle();
21995            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21996            if (uidArr != null) {
21997                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21998            }
21999            if (replacing) {
22000                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22001            }
22002            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22003                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22004            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22005        }
22006    }
22007
22008    private void loadPrivatePackages(final VolumeInfo vol) {
22009        mHandler.post(new Runnable() {
22010            @Override
22011            public void run() {
22012                loadPrivatePackagesInner(vol);
22013            }
22014        });
22015    }
22016
22017    private void loadPrivatePackagesInner(VolumeInfo vol) {
22018        final String volumeUuid = vol.fsUuid;
22019        if (TextUtils.isEmpty(volumeUuid)) {
22020            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22021            return;
22022        }
22023
22024        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22025        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22026        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22027
22028        final VersionInfo ver;
22029        final List<PackageSetting> packages;
22030        synchronized (mPackages) {
22031            ver = mSettings.findOrCreateVersion(volumeUuid);
22032            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22033        }
22034
22035        for (PackageSetting ps : packages) {
22036            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22037            synchronized (mInstallLock) {
22038                final PackageParser.Package pkg;
22039                try {
22040                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22041                    loaded.add(pkg.applicationInfo);
22042
22043                } catch (PackageManagerException e) {
22044                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22045                }
22046
22047                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22048                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22049                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22050                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22051                }
22052            }
22053        }
22054
22055        // Reconcile app data for all started/unlocked users
22056        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22057        final UserManager um = mContext.getSystemService(UserManager.class);
22058        UserManagerInternal umInternal = getUserManagerInternal();
22059        for (UserInfo user : um.getUsers()) {
22060            final int flags;
22061            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22062                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22063            } else if (umInternal.isUserRunning(user.id)) {
22064                flags = StorageManager.FLAG_STORAGE_DE;
22065            } else {
22066                continue;
22067            }
22068
22069            try {
22070                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22071                synchronized (mInstallLock) {
22072                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22073                }
22074            } catch (IllegalStateException e) {
22075                // Device was probably ejected, and we'll process that event momentarily
22076                Slog.w(TAG, "Failed to prepare storage: " + e);
22077            }
22078        }
22079
22080        synchronized (mPackages) {
22081            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22082            if (sdkUpdated) {
22083                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22084                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22085            }
22086            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22087                    mPermissionCallback);
22088
22089            // Yay, everything is now upgraded
22090            ver.forceCurrent();
22091
22092            mSettings.writeLPr();
22093        }
22094
22095        for (PackageFreezer freezer : freezers) {
22096            freezer.close();
22097        }
22098
22099        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22100        sendResourcesChangedBroadcast(true, false, loaded, null);
22101        mLoadedVolumes.add(vol.getId());
22102    }
22103
22104    private void unloadPrivatePackages(final VolumeInfo vol) {
22105        mHandler.post(new Runnable() {
22106            @Override
22107            public void run() {
22108                unloadPrivatePackagesInner(vol);
22109            }
22110        });
22111    }
22112
22113    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22114        final String volumeUuid = vol.fsUuid;
22115        if (TextUtils.isEmpty(volumeUuid)) {
22116            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22117            return;
22118        }
22119
22120        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22121        synchronized (mInstallLock) {
22122        synchronized (mPackages) {
22123            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22124            for (PackageSetting ps : packages) {
22125                if (ps.pkg == null) continue;
22126
22127                final ApplicationInfo info = ps.pkg.applicationInfo;
22128                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22129                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22130
22131                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22132                        "unloadPrivatePackagesInner")) {
22133                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22134                            false, null)) {
22135                        unloaded.add(info);
22136                    } else {
22137                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22138                    }
22139                }
22140
22141                // Try very hard to release any references to this package
22142                // so we don't risk the system server being killed due to
22143                // open FDs
22144                AttributeCache.instance().removePackage(ps.name);
22145            }
22146
22147            mSettings.writeLPr();
22148        }
22149        }
22150
22151        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22152        sendResourcesChangedBroadcast(false, false, unloaded, null);
22153        mLoadedVolumes.remove(vol.getId());
22154
22155        // Try very hard to release any references to this path so we don't risk
22156        // the system server being killed due to open FDs
22157        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22158
22159        for (int i = 0; i < 3; i++) {
22160            System.gc();
22161            System.runFinalization();
22162        }
22163    }
22164
22165    private void assertPackageKnown(String volumeUuid, String packageName)
22166            throws PackageManagerException {
22167        synchronized (mPackages) {
22168            // Normalize package name to handle renamed packages
22169            packageName = normalizePackageNameLPr(packageName);
22170
22171            final PackageSetting ps = mSettings.mPackages.get(packageName);
22172            if (ps == null) {
22173                throw new PackageManagerException("Package " + packageName + " is unknown");
22174            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22175                throw new PackageManagerException(
22176                        "Package " + packageName + " found on unknown volume " + volumeUuid
22177                                + "; expected volume " + ps.volumeUuid);
22178            }
22179        }
22180    }
22181
22182    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22183            throws PackageManagerException {
22184        synchronized (mPackages) {
22185            // Normalize package name to handle renamed packages
22186            packageName = normalizePackageNameLPr(packageName);
22187
22188            final PackageSetting ps = mSettings.mPackages.get(packageName);
22189            if (ps == null) {
22190                throw new PackageManagerException("Package " + packageName + " is unknown");
22191            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22192                throw new PackageManagerException(
22193                        "Package " + packageName + " found on unknown volume " + volumeUuid
22194                                + "; expected volume " + ps.volumeUuid);
22195            } else if (!ps.getInstalled(userId)) {
22196                throw new PackageManagerException(
22197                        "Package " + packageName + " not installed for user " + userId);
22198            }
22199        }
22200    }
22201
22202    private List<String> collectAbsoluteCodePaths() {
22203        synchronized (mPackages) {
22204            List<String> codePaths = new ArrayList<>();
22205            final int packageCount = mSettings.mPackages.size();
22206            for (int i = 0; i < packageCount; i++) {
22207                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22208                codePaths.add(ps.codePath.getAbsolutePath());
22209            }
22210            return codePaths;
22211        }
22212    }
22213
22214    /**
22215     * Examine all apps present on given mounted volume, and destroy apps that
22216     * aren't expected, either due to uninstallation or reinstallation on
22217     * another volume.
22218     */
22219    private void reconcileApps(String volumeUuid) {
22220        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22221        List<File> filesToDelete = null;
22222
22223        final File[] files = FileUtils.listFilesOrEmpty(
22224                Environment.getDataAppDirectory(volumeUuid));
22225        for (File file : files) {
22226            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22227                    && !PackageInstallerService.isStageName(file.getName());
22228            if (!isPackage) {
22229                // Ignore entries which are not packages
22230                continue;
22231            }
22232
22233            String absolutePath = file.getAbsolutePath();
22234
22235            boolean pathValid = false;
22236            final int absoluteCodePathCount = absoluteCodePaths.size();
22237            for (int i = 0; i < absoluteCodePathCount; i++) {
22238                String absoluteCodePath = absoluteCodePaths.get(i);
22239                if (absolutePath.startsWith(absoluteCodePath)) {
22240                    pathValid = true;
22241                    break;
22242                }
22243            }
22244
22245            if (!pathValid) {
22246                if (filesToDelete == null) {
22247                    filesToDelete = new ArrayList<>();
22248                }
22249                filesToDelete.add(file);
22250            }
22251        }
22252
22253        if (filesToDelete != null) {
22254            final int fileToDeleteCount = filesToDelete.size();
22255            for (int i = 0; i < fileToDeleteCount; i++) {
22256                File fileToDelete = filesToDelete.get(i);
22257                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22258                synchronized (mInstallLock) {
22259                    removeCodePathLI(fileToDelete);
22260                }
22261            }
22262        }
22263    }
22264
22265    /**
22266     * Reconcile all app data for the given user.
22267     * <p>
22268     * Verifies that directories exist and that ownership and labeling is
22269     * correct for all installed apps on all mounted volumes.
22270     */
22271    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22272        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22273        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22274            final String volumeUuid = vol.getFsUuid();
22275            synchronized (mInstallLock) {
22276                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22277            }
22278        }
22279    }
22280
22281    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22282            boolean migrateAppData) {
22283        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22284    }
22285
22286    /**
22287     * Reconcile all app data on given mounted volume.
22288     * <p>
22289     * Destroys app data that isn't expected, either due to uninstallation or
22290     * reinstallation on another volume.
22291     * <p>
22292     * Verifies that directories exist and that ownership and labeling is
22293     * correct for all installed apps.
22294     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22295     */
22296    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22297            boolean migrateAppData, boolean onlyCoreApps) {
22298        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22299                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22300        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22301
22302        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22303        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22304
22305        // First look for stale data that doesn't belong, and check if things
22306        // have changed since we did our last restorecon
22307        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22308            if (StorageManager.isFileEncryptedNativeOrEmulated()
22309                    && !StorageManager.isUserKeyUnlocked(userId)) {
22310                throw new RuntimeException(
22311                        "Yikes, someone asked us to reconcile CE storage while " + userId
22312                                + " was still locked; this would have caused massive data loss!");
22313            }
22314
22315            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22316            for (File file : files) {
22317                final String packageName = file.getName();
22318                try {
22319                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22320                } catch (PackageManagerException e) {
22321                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22322                    try {
22323                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22324                                StorageManager.FLAG_STORAGE_CE, 0);
22325                    } catch (InstallerException e2) {
22326                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22327                    }
22328                }
22329            }
22330        }
22331        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22332            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22333            for (File file : files) {
22334                final String packageName = file.getName();
22335                try {
22336                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22337                } catch (PackageManagerException e) {
22338                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22339                    try {
22340                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22341                                StorageManager.FLAG_STORAGE_DE, 0);
22342                    } catch (InstallerException e2) {
22343                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22344                    }
22345                }
22346            }
22347        }
22348
22349        // Ensure that data directories are ready to roll for all packages
22350        // installed for this volume and user
22351        final List<PackageSetting> packages;
22352        synchronized (mPackages) {
22353            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22354        }
22355        int preparedCount = 0;
22356        for (PackageSetting ps : packages) {
22357            final String packageName = ps.name;
22358            if (ps.pkg == null) {
22359                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22360                // TODO: might be due to legacy ASEC apps; we should circle back
22361                // and reconcile again once they're scanned
22362                continue;
22363            }
22364            // Skip non-core apps if requested
22365            if (onlyCoreApps && !ps.pkg.coreApp) {
22366                result.add(packageName);
22367                continue;
22368            }
22369
22370            if (ps.getInstalled(userId)) {
22371                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22372                preparedCount++;
22373            }
22374        }
22375
22376        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22377        return result;
22378    }
22379
22380    /**
22381     * Prepare app data for the given app just after it was installed or
22382     * upgraded. This method carefully only touches users that it's installed
22383     * for, and it forces a restorecon to handle any seinfo changes.
22384     * <p>
22385     * Verifies that directories exist and that ownership and labeling is
22386     * correct for all installed apps. If there is an ownership mismatch, it
22387     * will try recovering system apps by wiping data; third-party app data is
22388     * left intact.
22389     * <p>
22390     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22391     */
22392    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22393        final PackageSetting ps;
22394        synchronized (mPackages) {
22395            ps = mSettings.mPackages.get(pkg.packageName);
22396            mSettings.writeKernelMappingLPr(ps);
22397        }
22398
22399        final UserManager um = mContext.getSystemService(UserManager.class);
22400        UserManagerInternal umInternal = getUserManagerInternal();
22401        for (UserInfo user : um.getUsers()) {
22402            final int flags;
22403            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22404                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22405            } else if (umInternal.isUserRunning(user.id)) {
22406                flags = StorageManager.FLAG_STORAGE_DE;
22407            } else {
22408                continue;
22409            }
22410
22411            if (ps.getInstalled(user.id)) {
22412                // TODO: when user data is locked, mark that we're still dirty
22413                prepareAppDataLIF(pkg, user.id, flags);
22414            }
22415        }
22416    }
22417
22418    /**
22419     * Prepare app data for the given app.
22420     * <p>
22421     * Verifies that directories exist and that ownership and labeling is
22422     * correct for all installed apps. If there is an ownership mismatch, this
22423     * will try recovering system apps by wiping data; third-party app data is
22424     * left intact.
22425     */
22426    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22427        if (pkg == null) {
22428            Slog.wtf(TAG, "Package was null!", new Throwable());
22429            return;
22430        }
22431        prepareAppDataLeafLIF(pkg, userId, flags);
22432        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22433        for (int i = 0; i < childCount; i++) {
22434            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22435        }
22436    }
22437
22438    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22439            boolean maybeMigrateAppData) {
22440        prepareAppDataLIF(pkg, userId, flags);
22441
22442        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22443            // We may have just shuffled around app data directories, so
22444            // prepare them one more time
22445            prepareAppDataLIF(pkg, userId, flags);
22446        }
22447    }
22448
22449    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22450        if (DEBUG_APP_DATA) {
22451            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22452                    + Integer.toHexString(flags));
22453        }
22454
22455        final PackageSetting ps;
22456        synchronized (mPackages) {
22457            ps = mSettings.mPackages.get(pkg.packageName);
22458        }
22459        final String volumeUuid = pkg.volumeUuid;
22460        final String packageName = pkg.packageName;
22461
22462        ApplicationInfo app = (ps == null)
22463                ? pkg.applicationInfo
22464                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22465        if (app == null) {
22466            app = pkg.applicationInfo;
22467        }
22468
22469        final int appId = UserHandle.getAppId(app.uid);
22470
22471        Preconditions.checkNotNull(app.seInfo);
22472
22473        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22474        long ceDataInode = -1;
22475        try {
22476            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22477                    appId, seInfo, app.targetSdkVersion);
22478        } catch (InstallerException e) {
22479            if (app.isSystemApp()) {
22480                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22481                        + ", but trying to recover: " + e);
22482                destroyAppDataLeafLIF(pkg, userId, flags);
22483                try {
22484                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22485                            appId, seInfo, app.targetSdkVersion);
22486                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22487                } catch (InstallerException e2) {
22488                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22489                }
22490            } else {
22491                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22492            }
22493        }
22494        // Prepare the application profiles only for upgrades and first boot (so that we don't
22495        // repeat the same operation at each boot).
22496        // We only have to cover the upgrade and first boot here because for app installs we
22497        // prepare the profiles before invoking dexopt (in installPackageLI).
22498        //
22499        // We also have to cover non system users because we do not call the usual install package
22500        // methods for them.
22501        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22502            mArtManagerService.prepareAppProfiles(pkg, userId);
22503        }
22504
22505        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22506            // TODO: mark this structure as dirty so we persist it!
22507            synchronized (mPackages) {
22508                if (ps != null) {
22509                    ps.setCeDataInode(ceDataInode, userId);
22510                }
22511            }
22512        }
22513
22514        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22515    }
22516
22517    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22518        if (pkg == null) {
22519            Slog.wtf(TAG, "Package was null!", new Throwable());
22520            return;
22521        }
22522        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22523        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22524        for (int i = 0; i < childCount; i++) {
22525            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22526        }
22527    }
22528
22529    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22530        final String volumeUuid = pkg.volumeUuid;
22531        final String packageName = pkg.packageName;
22532        final ApplicationInfo app = pkg.applicationInfo;
22533
22534        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22535            // Create a native library symlink only if we have native libraries
22536            // and if the native libraries are 32 bit libraries. We do not provide
22537            // this symlink for 64 bit libraries.
22538            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22539                final String nativeLibPath = app.nativeLibraryDir;
22540                try {
22541                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22542                            nativeLibPath, userId);
22543                } catch (InstallerException e) {
22544                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22545                }
22546            }
22547        }
22548    }
22549
22550    /**
22551     * For system apps on non-FBE devices, this method migrates any existing
22552     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22553     * requested by the app.
22554     */
22555    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22556        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22557                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22558            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22559                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22560            try {
22561                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22562                        storageTarget);
22563            } catch (InstallerException e) {
22564                logCriticalInfo(Log.WARN,
22565                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22566            }
22567            return true;
22568        } else {
22569            return false;
22570        }
22571    }
22572
22573    public PackageFreezer freezePackage(String packageName, String killReason) {
22574        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22575    }
22576
22577    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22578        return new PackageFreezer(packageName, userId, killReason);
22579    }
22580
22581    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22582            String killReason) {
22583        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22584    }
22585
22586    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22587            String killReason) {
22588        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22589            return new PackageFreezer();
22590        } else {
22591            return freezePackage(packageName, userId, killReason);
22592        }
22593    }
22594
22595    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22596            String killReason) {
22597        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22598    }
22599
22600    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22601            String killReason) {
22602        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22603            return new PackageFreezer();
22604        } else {
22605            return freezePackage(packageName, userId, killReason);
22606        }
22607    }
22608
22609    /**
22610     * Class that freezes and kills the given package upon creation, and
22611     * unfreezes it upon closing. This is typically used when doing surgery on
22612     * app code/data to prevent the app from running while you're working.
22613     */
22614    private class PackageFreezer implements AutoCloseable {
22615        private final String mPackageName;
22616        private final PackageFreezer[] mChildren;
22617
22618        private final boolean mWeFroze;
22619
22620        private final AtomicBoolean mClosed = new AtomicBoolean();
22621        private final CloseGuard mCloseGuard = CloseGuard.get();
22622
22623        /**
22624         * Create and return a stub freezer that doesn't actually do anything,
22625         * typically used when someone requested
22626         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22627         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22628         */
22629        public PackageFreezer() {
22630            mPackageName = null;
22631            mChildren = null;
22632            mWeFroze = false;
22633            mCloseGuard.open("close");
22634        }
22635
22636        public PackageFreezer(String packageName, int userId, String killReason) {
22637            synchronized (mPackages) {
22638                mPackageName = packageName;
22639                mWeFroze = mFrozenPackages.add(mPackageName);
22640
22641                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22642                if (ps != null) {
22643                    killApplication(ps.name, ps.appId, userId, killReason);
22644                }
22645
22646                final PackageParser.Package p = mPackages.get(packageName);
22647                if (p != null && p.childPackages != null) {
22648                    final int N = p.childPackages.size();
22649                    mChildren = new PackageFreezer[N];
22650                    for (int i = 0; i < N; i++) {
22651                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22652                                userId, killReason);
22653                    }
22654                } else {
22655                    mChildren = null;
22656                }
22657            }
22658            mCloseGuard.open("close");
22659        }
22660
22661        @Override
22662        protected void finalize() throws Throwable {
22663            try {
22664                if (mCloseGuard != null) {
22665                    mCloseGuard.warnIfOpen();
22666                }
22667
22668                close();
22669            } finally {
22670                super.finalize();
22671            }
22672        }
22673
22674        @Override
22675        public void close() {
22676            mCloseGuard.close();
22677            if (mClosed.compareAndSet(false, true)) {
22678                synchronized (mPackages) {
22679                    if (mWeFroze) {
22680                        mFrozenPackages.remove(mPackageName);
22681                    }
22682
22683                    if (mChildren != null) {
22684                        for (PackageFreezer freezer : mChildren) {
22685                            freezer.close();
22686                        }
22687                    }
22688                }
22689            }
22690        }
22691    }
22692
22693    /**
22694     * Verify that given package is currently frozen.
22695     */
22696    private void checkPackageFrozen(String packageName) {
22697        synchronized (mPackages) {
22698            if (!mFrozenPackages.contains(packageName)) {
22699                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22700            }
22701        }
22702    }
22703
22704    @Override
22705    public int movePackage(final String packageName, final String volumeUuid) {
22706        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22707
22708        final int callingUid = Binder.getCallingUid();
22709        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22710        final int moveId = mNextMoveId.getAndIncrement();
22711        mHandler.post(new Runnable() {
22712            @Override
22713            public void run() {
22714                try {
22715                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22716                } catch (PackageManagerException e) {
22717                    Slog.w(TAG, "Failed to move " + packageName, e);
22718                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22719                }
22720            }
22721        });
22722        return moveId;
22723    }
22724
22725    private void movePackageInternal(final String packageName, final String volumeUuid,
22726            final int moveId, final int callingUid, UserHandle user)
22727                    throws PackageManagerException {
22728        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22729        final PackageManager pm = mContext.getPackageManager();
22730
22731        final boolean currentAsec;
22732        final String currentVolumeUuid;
22733        final File codeFile;
22734        final String installerPackageName;
22735        final String packageAbiOverride;
22736        final int appId;
22737        final String seinfo;
22738        final String label;
22739        final int targetSdkVersion;
22740        final PackageFreezer freezer;
22741        final int[] installedUserIds;
22742
22743        // reader
22744        synchronized (mPackages) {
22745            final PackageParser.Package pkg = mPackages.get(packageName);
22746            final PackageSetting ps = mSettings.mPackages.get(packageName);
22747            if (pkg == null
22748                    || ps == null
22749                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22750                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22751            }
22752            if (pkg.applicationInfo.isSystemApp()) {
22753                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22754                        "Cannot move system application");
22755            }
22756
22757            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22758            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22759                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22760            if (isInternalStorage && !allow3rdPartyOnInternal) {
22761                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22762                        "3rd party apps are not allowed on internal storage");
22763            }
22764
22765            if (pkg.applicationInfo.isExternalAsec()) {
22766                currentAsec = true;
22767                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22768            } else if (pkg.applicationInfo.isForwardLocked()) {
22769                currentAsec = true;
22770                currentVolumeUuid = "forward_locked";
22771            } else {
22772                currentAsec = false;
22773                currentVolumeUuid = ps.volumeUuid;
22774
22775                final File probe = new File(pkg.codePath);
22776                final File probeOat = new File(probe, "oat");
22777                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22778                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22779                            "Move only supported for modern cluster style installs");
22780                }
22781            }
22782
22783            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22784                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22785                        "Package already moved to " + volumeUuid);
22786            }
22787            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22788                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22789                        "Device admin cannot be moved");
22790            }
22791
22792            if (mFrozenPackages.contains(packageName)) {
22793                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22794                        "Failed to move already frozen package");
22795            }
22796
22797            codeFile = new File(pkg.codePath);
22798            installerPackageName = ps.installerPackageName;
22799            packageAbiOverride = ps.cpuAbiOverrideString;
22800            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22801            seinfo = pkg.applicationInfo.seInfo;
22802            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22803            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22804            freezer = freezePackage(packageName, "movePackageInternal");
22805            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22806        }
22807
22808        final Bundle extras = new Bundle();
22809        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22810        extras.putString(Intent.EXTRA_TITLE, label);
22811        mMoveCallbacks.notifyCreated(moveId, extras);
22812
22813        int installFlags;
22814        final boolean moveCompleteApp;
22815        final File measurePath;
22816
22817        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22818            installFlags = INSTALL_INTERNAL;
22819            moveCompleteApp = !currentAsec;
22820            measurePath = Environment.getDataAppDirectory(volumeUuid);
22821        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22822            installFlags = INSTALL_EXTERNAL;
22823            moveCompleteApp = false;
22824            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22825        } else {
22826            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22827            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22828                    || !volume.isMountedWritable()) {
22829                freezer.close();
22830                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22831                        "Move location not mounted private volume");
22832            }
22833
22834            Preconditions.checkState(!currentAsec);
22835
22836            installFlags = INSTALL_INTERNAL;
22837            moveCompleteApp = true;
22838            measurePath = Environment.getDataAppDirectory(volumeUuid);
22839        }
22840
22841        // If we're moving app data around, we need all the users unlocked
22842        if (moveCompleteApp) {
22843            for (int userId : installedUserIds) {
22844                if (StorageManager.isFileEncryptedNativeOrEmulated()
22845                        && !StorageManager.isUserKeyUnlocked(userId)) {
22846                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22847                            "User " + userId + " must be unlocked");
22848                }
22849            }
22850        }
22851
22852        final PackageStats stats = new PackageStats(null, -1);
22853        synchronized (mInstaller) {
22854            for (int userId : installedUserIds) {
22855                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22856                    freezer.close();
22857                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22858                            "Failed to measure package size");
22859                }
22860            }
22861        }
22862
22863        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22864                + stats.dataSize);
22865
22866        final long startFreeBytes = measurePath.getUsableSpace();
22867        final long sizeBytes;
22868        if (moveCompleteApp) {
22869            sizeBytes = stats.codeSize + stats.dataSize;
22870        } else {
22871            sizeBytes = stats.codeSize;
22872        }
22873
22874        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22875            freezer.close();
22876            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22877                    "Not enough free space to move");
22878        }
22879
22880        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22881
22882        final CountDownLatch installedLatch = new CountDownLatch(1);
22883        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22884            @Override
22885            public void onUserActionRequired(Intent intent) throws RemoteException {
22886                throw new IllegalStateException();
22887            }
22888
22889            @Override
22890            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22891                    Bundle extras) throws RemoteException {
22892                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22893                        + PackageManager.installStatusToString(returnCode, msg));
22894
22895                installedLatch.countDown();
22896                freezer.close();
22897
22898                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22899                switch (status) {
22900                    case PackageInstaller.STATUS_SUCCESS:
22901                        mMoveCallbacks.notifyStatusChanged(moveId,
22902                                PackageManager.MOVE_SUCCEEDED);
22903                        break;
22904                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22905                        mMoveCallbacks.notifyStatusChanged(moveId,
22906                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22907                        break;
22908                    default:
22909                        mMoveCallbacks.notifyStatusChanged(moveId,
22910                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22911                        break;
22912                }
22913            }
22914        };
22915
22916        final MoveInfo move;
22917        if (moveCompleteApp) {
22918            // Kick off a thread to report progress estimates
22919            new Thread() {
22920                @Override
22921                public void run() {
22922                    while (true) {
22923                        try {
22924                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22925                                break;
22926                            }
22927                        } catch (InterruptedException ignored) {
22928                        }
22929
22930                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22931                        final int progress = 10 + (int) MathUtils.constrain(
22932                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22933                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22934                    }
22935                }
22936            }.start();
22937
22938            final String dataAppName = codeFile.getName();
22939            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22940                    dataAppName, appId, seinfo, targetSdkVersion);
22941        } else {
22942            move = null;
22943        }
22944
22945        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22946
22947        final Message msg = mHandler.obtainMessage(INIT_COPY);
22948        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22949        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22950                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22951                packageAbiOverride, null /*grantedPermissions*/,
22952                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22953        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22954        msg.obj = params;
22955
22956        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22957                System.identityHashCode(msg.obj));
22958        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22959                System.identityHashCode(msg.obj));
22960
22961        mHandler.sendMessage(msg);
22962    }
22963
22964    @Override
22965    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22966        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22967
22968        final int realMoveId = mNextMoveId.getAndIncrement();
22969        final Bundle extras = new Bundle();
22970        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22971        mMoveCallbacks.notifyCreated(realMoveId, extras);
22972
22973        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22974            @Override
22975            public void onCreated(int moveId, Bundle extras) {
22976                // Ignored
22977            }
22978
22979            @Override
22980            public void onStatusChanged(int moveId, int status, long estMillis) {
22981                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22982            }
22983        };
22984
22985        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22986        storage.setPrimaryStorageUuid(volumeUuid, callback);
22987        return realMoveId;
22988    }
22989
22990    @Override
22991    public int getMoveStatus(int moveId) {
22992        mContext.enforceCallingOrSelfPermission(
22993                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22994        return mMoveCallbacks.mLastStatus.get(moveId);
22995    }
22996
22997    @Override
22998    public void registerMoveCallback(IPackageMoveObserver callback) {
22999        mContext.enforceCallingOrSelfPermission(
23000                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23001        mMoveCallbacks.register(callback);
23002    }
23003
23004    @Override
23005    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23006        mContext.enforceCallingOrSelfPermission(
23007                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23008        mMoveCallbacks.unregister(callback);
23009    }
23010
23011    @Override
23012    public boolean setInstallLocation(int loc) {
23013        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23014                null);
23015        if (getInstallLocation() == loc) {
23016            return true;
23017        }
23018        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23019                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23020            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23021                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23022            return true;
23023        }
23024        return false;
23025   }
23026
23027    @Override
23028    public int getInstallLocation() {
23029        // allow instant app access
23030        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23031                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23032                PackageHelper.APP_INSTALL_AUTO);
23033    }
23034
23035    /** Called by UserManagerService */
23036    void cleanUpUser(UserManagerService userManager, int userHandle) {
23037        synchronized (mPackages) {
23038            mDirtyUsers.remove(userHandle);
23039            mUserNeedsBadging.delete(userHandle);
23040            mSettings.removeUserLPw(userHandle);
23041            mPendingBroadcasts.remove(userHandle);
23042            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23043            removeUnusedPackagesLPw(userManager, userHandle);
23044        }
23045    }
23046
23047    /**
23048     * We're removing userHandle and would like to remove any downloaded packages
23049     * that are no longer in use by any other user.
23050     * @param userHandle the user being removed
23051     */
23052    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23053        final boolean DEBUG_CLEAN_APKS = false;
23054        int [] users = userManager.getUserIds();
23055        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23056        while (psit.hasNext()) {
23057            PackageSetting ps = psit.next();
23058            if (ps.pkg == null) {
23059                continue;
23060            }
23061            final String packageName = ps.pkg.packageName;
23062            // Skip over if system app
23063            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23064                continue;
23065            }
23066            if (DEBUG_CLEAN_APKS) {
23067                Slog.i(TAG, "Checking package " + packageName);
23068            }
23069            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23070            if (keep) {
23071                if (DEBUG_CLEAN_APKS) {
23072                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23073                }
23074            } else {
23075                for (int i = 0; i < users.length; i++) {
23076                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23077                        keep = true;
23078                        if (DEBUG_CLEAN_APKS) {
23079                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23080                                    + users[i]);
23081                        }
23082                        break;
23083                    }
23084                }
23085            }
23086            if (!keep) {
23087                if (DEBUG_CLEAN_APKS) {
23088                    Slog.i(TAG, "  Removing package " + packageName);
23089                }
23090                mHandler.post(new Runnable() {
23091                    public void run() {
23092                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23093                                userHandle, 0);
23094                    } //end run
23095                });
23096            }
23097        }
23098    }
23099
23100    /** Called by UserManagerService */
23101    void createNewUser(int userId, String[] disallowedPackages) {
23102        synchronized (mInstallLock) {
23103            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23104        }
23105        synchronized (mPackages) {
23106            scheduleWritePackageRestrictionsLocked(userId);
23107            scheduleWritePackageListLocked(userId);
23108            applyFactoryDefaultBrowserLPw(userId);
23109            primeDomainVerificationsLPw(userId);
23110        }
23111    }
23112
23113    void onNewUserCreated(final int userId) {
23114        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23115        synchronized(mPackages) {
23116            // If permission review for legacy apps is required, we represent
23117            // dagerous permissions for such apps as always granted runtime
23118            // permissions to keep per user flag state whether review is needed.
23119            // Hence, if a new user is added we have to propagate dangerous
23120            // permission grants for these legacy apps.
23121            if (mSettings.mPermissions.mPermissionReviewRequired) {
23122// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23123                mPermissionManager.updateAllPermissions(
23124                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23125                        mPermissionCallback);
23126            }
23127        }
23128    }
23129
23130    @Override
23131    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23132        mContext.enforceCallingOrSelfPermission(
23133                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23134                "Only package verification agents can read the verifier device identity");
23135
23136        synchronized (mPackages) {
23137            return mSettings.getVerifierDeviceIdentityLPw();
23138        }
23139    }
23140
23141    @Override
23142    public void setPermissionEnforced(String permission, boolean enforced) {
23143        // TODO: Now that we no longer change GID for storage, this should to away.
23144        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23145                "setPermissionEnforced");
23146        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23147            synchronized (mPackages) {
23148                if (mSettings.mReadExternalStorageEnforced == null
23149                        || mSettings.mReadExternalStorageEnforced != enforced) {
23150                    mSettings.mReadExternalStorageEnforced =
23151                            enforced ? Boolean.TRUE : Boolean.FALSE;
23152                    mSettings.writeLPr();
23153                }
23154            }
23155            // kill any non-foreground processes so we restart them and
23156            // grant/revoke the GID.
23157            final IActivityManager am = ActivityManager.getService();
23158            if (am != null) {
23159                final long token = Binder.clearCallingIdentity();
23160                try {
23161                    am.killProcessesBelowForeground("setPermissionEnforcement");
23162                } catch (RemoteException e) {
23163                } finally {
23164                    Binder.restoreCallingIdentity(token);
23165                }
23166            }
23167        } else {
23168            throw new IllegalArgumentException("No selective enforcement for " + permission);
23169        }
23170    }
23171
23172    @Override
23173    @Deprecated
23174    public boolean isPermissionEnforced(String permission) {
23175        // allow instant applications
23176        return true;
23177    }
23178
23179    @Override
23180    public boolean isStorageLow() {
23181        // allow instant applications
23182        final long token = Binder.clearCallingIdentity();
23183        try {
23184            final DeviceStorageMonitorInternal
23185                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23186            if (dsm != null) {
23187                return dsm.isMemoryLow();
23188            } else {
23189                return false;
23190            }
23191        } finally {
23192            Binder.restoreCallingIdentity(token);
23193        }
23194    }
23195
23196    @Override
23197    public IPackageInstaller getPackageInstaller() {
23198        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23199            return null;
23200        }
23201        return mInstallerService;
23202    }
23203
23204    @Override
23205    public IArtManager getArtManager() {
23206        return mArtManagerService;
23207    }
23208
23209    private boolean userNeedsBadging(int userId) {
23210        int index = mUserNeedsBadging.indexOfKey(userId);
23211        if (index < 0) {
23212            final UserInfo userInfo;
23213            final long token = Binder.clearCallingIdentity();
23214            try {
23215                userInfo = sUserManager.getUserInfo(userId);
23216            } finally {
23217                Binder.restoreCallingIdentity(token);
23218            }
23219            final boolean b;
23220            if (userInfo != null && userInfo.isManagedProfile()) {
23221                b = true;
23222            } else {
23223                b = false;
23224            }
23225            mUserNeedsBadging.put(userId, b);
23226            return b;
23227        }
23228        return mUserNeedsBadging.valueAt(index);
23229    }
23230
23231    @Override
23232    public KeySet getKeySetByAlias(String packageName, String alias) {
23233        if (packageName == null || alias == null) {
23234            return null;
23235        }
23236        synchronized(mPackages) {
23237            final PackageParser.Package pkg = mPackages.get(packageName);
23238            if (pkg == null) {
23239                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23240                throw new IllegalArgumentException("Unknown package: " + packageName);
23241            }
23242            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23243            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23244                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23245                throw new IllegalArgumentException("Unknown package: " + packageName);
23246            }
23247            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23248            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23249        }
23250    }
23251
23252    @Override
23253    public KeySet getSigningKeySet(String packageName) {
23254        if (packageName == null) {
23255            return null;
23256        }
23257        synchronized(mPackages) {
23258            final int callingUid = Binder.getCallingUid();
23259            final int callingUserId = UserHandle.getUserId(callingUid);
23260            final PackageParser.Package pkg = mPackages.get(packageName);
23261            if (pkg == null) {
23262                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23263                throw new IllegalArgumentException("Unknown package: " + packageName);
23264            }
23265            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23266            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23267                // filter and pretend the package doesn't exist
23268                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23269                        + ", uid:" + callingUid);
23270                throw new IllegalArgumentException("Unknown package: " + packageName);
23271            }
23272            if (pkg.applicationInfo.uid != callingUid
23273                    && Process.SYSTEM_UID != callingUid) {
23274                throw new SecurityException("May not access signing KeySet of other apps.");
23275            }
23276            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23277            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23278        }
23279    }
23280
23281    @Override
23282    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23283        final int callingUid = Binder.getCallingUid();
23284        if (getInstantAppPackageName(callingUid) != null) {
23285            return false;
23286        }
23287        if (packageName == null || ks == null) {
23288            return false;
23289        }
23290        synchronized(mPackages) {
23291            final PackageParser.Package pkg = mPackages.get(packageName);
23292            if (pkg == null
23293                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23294                            UserHandle.getUserId(callingUid))) {
23295                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23296                throw new IllegalArgumentException("Unknown package: " + packageName);
23297            }
23298            IBinder ksh = ks.getToken();
23299            if (ksh instanceof KeySetHandle) {
23300                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23301                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23302            }
23303            return false;
23304        }
23305    }
23306
23307    @Override
23308    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23309        final int callingUid = Binder.getCallingUid();
23310        if (getInstantAppPackageName(callingUid) != null) {
23311            return false;
23312        }
23313        if (packageName == null || ks == null) {
23314            return false;
23315        }
23316        synchronized(mPackages) {
23317            final PackageParser.Package pkg = mPackages.get(packageName);
23318            if (pkg == null
23319                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23320                            UserHandle.getUserId(callingUid))) {
23321                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23322                throw new IllegalArgumentException("Unknown package: " + packageName);
23323            }
23324            IBinder ksh = ks.getToken();
23325            if (ksh instanceof KeySetHandle) {
23326                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23327                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23328            }
23329            return false;
23330        }
23331    }
23332
23333    private void deletePackageIfUnusedLPr(final String packageName) {
23334        PackageSetting ps = mSettings.mPackages.get(packageName);
23335        if (ps == null) {
23336            return;
23337        }
23338        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23339            // TODO Implement atomic delete if package is unused
23340            // It is currently possible that the package will be deleted even if it is installed
23341            // after this method returns.
23342            mHandler.post(new Runnable() {
23343                public void run() {
23344                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23345                            0, PackageManager.DELETE_ALL_USERS);
23346                }
23347            });
23348        }
23349    }
23350
23351    /**
23352     * Check and throw if the given before/after packages would be considered a
23353     * downgrade.
23354     */
23355    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23356            throws PackageManagerException {
23357        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23358            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23359                    "Update version code " + after.versionCode + " is older than current "
23360                    + before.getLongVersionCode());
23361        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23362            if (after.baseRevisionCode < before.baseRevisionCode) {
23363                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23364                        "Update base revision code " + after.baseRevisionCode
23365                        + " is older than current " + before.baseRevisionCode);
23366            }
23367
23368            if (!ArrayUtils.isEmpty(after.splitNames)) {
23369                for (int i = 0; i < after.splitNames.length; i++) {
23370                    final String splitName = after.splitNames[i];
23371                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23372                    if (j != -1) {
23373                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23374                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23375                                    "Update split " + splitName + " revision code "
23376                                    + after.splitRevisionCodes[i] + " is older than current "
23377                                    + before.splitRevisionCodes[j]);
23378                        }
23379                    }
23380                }
23381            }
23382        }
23383    }
23384
23385    private static class MoveCallbacks extends Handler {
23386        private static final int MSG_CREATED = 1;
23387        private static final int MSG_STATUS_CHANGED = 2;
23388
23389        private final RemoteCallbackList<IPackageMoveObserver>
23390                mCallbacks = new RemoteCallbackList<>();
23391
23392        private final SparseIntArray mLastStatus = new SparseIntArray();
23393
23394        public MoveCallbacks(Looper looper) {
23395            super(looper);
23396        }
23397
23398        public void register(IPackageMoveObserver callback) {
23399            mCallbacks.register(callback);
23400        }
23401
23402        public void unregister(IPackageMoveObserver callback) {
23403            mCallbacks.unregister(callback);
23404        }
23405
23406        @Override
23407        public void handleMessage(Message msg) {
23408            final SomeArgs args = (SomeArgs) msg.obj;
23409            final int n = mCallbacks.beginBroadcast();
23410            for (int i = 0; i < n; i++) {
23411                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23412                try {
23413                    invokeCallback(callback, msg.what, args);
23414                } catch (RemoteException ignored) {
23415                }
23416            }
23417            mCallbacks.finishBroadcast();
23418            args.recycle();
23419        }
23420
23421        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23422                throws RemoteException {
23423            switch (what) {
23424                case MSG_CREATED: {
23425                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23426                    break;
23427                }
23428                case MSG_STATUS_CHANGED: {
23429                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23430                    break;
23431                }
23432            }
23433        }
23434
23435        private void notifyCreated(int moveId, Bundle extras) {
23436            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23437
23438            final SomeArgs args = SomeArgs.obtain();
23439            args.argi1 = moveId;
23440            args.arg2 = extras;
23441            obtainMessage(MSG_CREATED, args).sendToTarget();
23442        }
23443
23444        private void notifyStatusChanged(int moveId, int status) {
23445            notifyStatusChanged(moveId, status, -1);
23446        }
23447
23448        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23449            Slog.v(TAG, "Move " + moveId + " status " + status);
23450
23451            final SomeArgs args = SomeArgs.obtain();
23452            args.argi1 = moveId;
23453            args.argi2 = status;
23454            args.arg3 = estMillis;
23455            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23456
23457            synchronized (mLastStatus) {
23458                mLastStatus.put(moveId, status);
23459            }
23460        }
23461    }
23462
23463    private final static class OnPermissionChangeListeners extends Handler {
23464        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23465
23466        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23467                new RemoteCallbackList<>();
23468
23469        public OnPermissionChangeListeners(Looper looper) {
23470            super(looper);
23471        }
23472
23473        @Override
23474        public void handleMessage(Message msg) {
23475            switch (msg.what) {
23476                case MSG_ON_PERMISSIONS_CHANGED: {
23477                    final int uid = msg.arg1;
23478                    handleOnPermissionsChanged(uid);
23479                } break;
23480            }
23481        }
23482
23483        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23484            mPermissionListeners.register(listener);
23485
23486        }
23487
23488        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23489            mPermissionListeners.unregister(listener);
23490        }
23491
23492        public void onPermissionsChanged(int uid) {
23493            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23494                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23495            }
23496        }
23497
23498        private void handleOnPermissionsChanged(int uid) {
23499            final int count = mPermissionListeners.beginBroadcast();
23500            try {
23501                for (int i = 0; i < count; i++) {
23502                    IOnPermissionsChangeListener callback = mPermissionListeners
23503                            .getBroadcastItem(i);
23504                    try {
23505                        callback.onPermissionsChanged(uid);
23506                    } catch (RemoteException e) {
23507                        Log.e(TAG, "Permission listener is dead", e);
23508                    }
23509                }
23510            } finally {
23511                mPermissionListeners.finishBroadcast();
23512            }
23513        }
23514    }
23515
23516    private class PackageManagerNative extends IPackageManagerNative.Stub {
23517        @Override
23518        public String[] getNamesForUids(int[] uids) throws RemoteException {
23519            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23520            // massage results so they can be parsed by the native binder
23521            for (int i = results.length - 1; i >= 0; --i) {
23522                if (results[i] == null) {
23523                    results[i] = "";
23524                }
23525            }
23526            return results;
23527        }
23528
23529        // NB: this differentiates between preloads and sideloads
23530        @Override
23531        public String getInstallerForPackage(String packageName) throws RemoteException {
23532            final String installerName = getInstallerPackageName(packageName);
23533            if (!TextUtils.isEmpty(installerName)) {
23534                return installerName;
23535            }
23536            // differentiate between preload and sideload
23537            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23538            ApplicationInfo appInfo = getApplicationInfo(packageName,
23539                                    /*flags*/ 0,
23540                                    /*userId*/ callingUser);
23541            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23542                return "preload";
23543            }
23544            return "";
23545        }
23546
23547        @Override
23548        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23549            try {
23550                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23551                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23552                if (pInfo != null) {
23553                    return pInfo.getLongVersionCode();
23554                }
23555            } catch (Exception e) {
23556            }
23557            return 0;
23558        }
23559    }
23560
23561    private class PackageManagerInternalImpl extends PackageManagerInternal {
23562        @Override
23563        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23564                int flagValues, int userId) {
23565            PackageManagerService.this.updatePermissionFlags(
23566                    permName, packageName, flagMask, flagValues, userId);
23567        }
23568
23569        @Override
23570        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23571            SigningDetails sd = getSigningDetails(packageName);
23572            if (sd == null) {
23573                return false;
23574            }
23575            return sd.hasSha256Certificate(restoringFromSigHash,
23576                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23577        }
23578
23579        @Override
23580        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23581            SigningDetails sd = getSigningDetails(packageName);
23582            if (sd == null) {
23583                return false;
23584            }
23585            return sd.hasCertificate(restoringFromSig,
23586                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23587        }
23588
23589        @Override
23590        public boolean hasSignatureCapability(int serverUid, int clientUid,
23591                @SigningDetails.CertCapabilities int capability) {
23592            SigningDetails serverSigningDetails = getSigningDetails(serverUid);
23593            SigningDetails clientSigningDetails = getSigningDetails(clientUid);
23594            return serverSigningDetails.checkCapability(clientSigningDetails, capability)
23595                    || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
23596
23597        }
23598
23599        private SigningDetails getSigningDetails(@NonNull String packageName) {
23600            synchronized (mPackages) {
23601                PackageParser.Package p = mPackages.get(packageName);
23602                if (p == null) {
23603                    return null;
23604                }
23605                return p.mSigningDetails;
23606            }
23607        }
23608
23609        private SigningDetails getSigningDetails(int uid) {
23610            synchronized (mPackages) {
23611                final int appId = UserHandle.getAppId(uid);
23612                final Object obj = mSettings.getUserIdLPr(appId);
23613                if (obj != null) {
23614                    if (obj instanceof SharedUserSetting) {
23615                        return ((SharedUserSetting) obj).signatures.mSigningDetails;
23616                    } else if (obj instanceof PackageSetting) {
23617                        final PackageSetting ps = (PackageSetting) obj;
23618                        return ps.signatures.mSigningDetails;
23619                    }
23620                }
23621                return SigningDetails.UNKNOWN;
23622            }
23623        }
23624
23625        @Override
23626        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23627            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23628        }
23629
23630        @Override
23631        public boolean isInstantApp(String packageName, int userId) {
23632            return PackageManagerService.this.isInstantApp(packageName, userId);
23633        }
23634
23635        @Override
23636        public String getInstantAppPackageName(int uid) {
23637            return PackageManagerService.this.getInstantAppPackageName(uid);
23638        }
23639
23640        @Override
23641        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23642            synchronized (mPackages) {
23643                return PackageManagerService.this.filterAppAccessLPr(
23644                        (PackageSetting) pkg.mExtras, callingUid, userId);
23645            }
23646        }
23647
23648        @Override
23649        public PackageParser.Package getPackage(String packageName) {
23650            synchronized (mPackages) {
23651                packageName = resolveInternalPackageNameLPr(
23652                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23653                return mPackages.get(packageName);
23654            }
23655        }
23656
23657        @Override
23658        public PackageList getPackageList(PackageListObserver observer) {
23659            synchronized (mPackages) {
23660                final int N = mPackages.size();
23661                final ArrayList<String> list = new ArrayList<>(N);
23662                for (int i = 0; i < N; i++) {
23663                    list.add(mPackages.keyAt(i));
23664                }
23665                final PackageList packageList = new PackageList(list, observer);
23666                if (observer != null) {
23667                    mPackageListObservers.add(packageList);
23668                }
23669                return packageList;
23670            }
23671        }
23672
23673        @Override
23674        public void removePackageListObserver(PackageListObserver observer) {
23675            synchronized (mPackages) {
23676                mPackageListObservers.remove(observer);
23677            }
23678        }
23679
23680        @Override
23681        public PackageParser.Package getDisabledPackage(String packageName) {
23682            synchronized (mPackages) {
23683                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23684                return (ps != null) ? ps.pkg : null;
23685            }
23686        }
23687
23688        @Override
23689        public String getKnownPackageName(int knownPackage, int userId) {
23690            switch(knownPackage) {
23691                case PackageManagerInternal.PACKAGE_BROWSER:
23692                    return getDefaultBrowserPackageName(userId);
23693                case PackageManagerInternal.PACKAGE_INSTALLER:
23694                    return mRequiredInstallerPackage;
23695                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23696                    return mSetupWizardPackage;
23697                case PackageManagerInternal.PACKAGE_SYSTEM:
23698                    return "android";
23699                case PackageManagerInternal.PACKAGE_VERIFIER:
23700                    return mRequiredVerifierPackage;
23701                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23702                    return mSystemTextClassifierPackage;
23703            }
23704            return null;
23705        }
23706
23707        @Override
23708        public boolean isResolveActivityComponent(ComponentInfo component) {
23709            return mResolveActivity.packageName.equals(component.packageName)
23710                    && mResolveActivity.name.equals(component.name);
23711        }
23712
23713        @Override
23714        public void setLocationPackagesProvider(PackagesProvider provider) {
23715            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23716        }
23717
23718        @Override
23719        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23720            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23721        }
23722
23723        @Override
23724        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23725            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23726        }
23727
23728        @Override
23729        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23730            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23731        }
23732
23733        @Override
23734        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23735            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23736        }
23737
23738        @Override
23739        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23740            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23741        }
23742
23743        @Override
23744        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23745            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23746        }
23747
23748        @Override
23749        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23750            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23751        }
23752
23753        @Override
23754        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23755            synchronized (mPackages) {
23756                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23757            }
23758            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23759        }
23760
23761        @Override
23762        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23763            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23764                    packageName, userId);
23765        }
23766
23767        @Override
23768        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23769            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23770                    packageName, userId);
23771        }
23772
23773        @Override
23774        public void setKeepUninstalledPackages(final List<String> packageList) {
23775            Preconditions.checkNotNull(packageList);
23776            List<String> removedFromList = null;
23777            synchronized (mPackages) {
23778                if (mKeepUninstalledPackages != null) {
23779                    final int packagesCount = mKeepUninstalledPackages.size();
23780                    for (int i = 0; i < packagesCount; i++) {
23781                        String oldPackage = mKeepUninstalledPackages.get(i);
23782                        if (packageList != null && packageList.contains(oldPackage)) {
23783                            continue;
23784                        }
23785                        if (removedFromList == null) {
23786                            removedFromList = new ArrayList<>();
23787                        }
23788                        removedFromList.add(oldPackage);
23789                    }
23790                }
23791                mKeepUninstalledPackages = new ArrayList<>(packageList);
23792                if (removedFromList != null) {
23793                    final int removedCount = removedFromList.size();
23794                    for (int i = 0; i < removedCount; i++) {
23795                        deletePackageIfUnusedLPr(removedFromList.get(i));
23796                    }
23797                }
23798            }
23799        }
23800
23801        @Override
23802        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23803            synchronized (mPackages) {
23804                return mPermissionManager.isPermissionsReviewRequired(
23805                        mPackages.get(packageName), userId);
23806            }
23807        }
23808
23809        @Override
23810        public PackageInfo getPackageInfo(
23811                String packageName, int flags, int filterCallingUid, int userId) {
23812            return PackageManagerService.this
23813                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23814                            flags, filterCallingUid, userId);
23815        }
23816
23817        @Override
23818        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23819            synchronized (mPackages) {
23820                final PackageSetting ps = mSettings.mPackages.get(packageName);
23821                PersistableBundle launcherExtras = null;
23822                if (ps != null) {
23823                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23824                }
23825                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23826            }
23827        }
23828
23829        @Override
23830        public boolean isPackageSuspended(String packageName, int userId) {
23831            synchronized (mPackages) {
23832                final PackageSetting ps = mSettings.mPackages.get(packageName);
23833                return (ps != null) ? ps.getSuspended(userId) : false;
23834            }
23835        }
23836
23837        @Override
23838        public String getSuspendingPackage(String suspendedPackage, int userId) {
23839            synchronized (mPackages) {
23840                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23841                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23842            }
23843        }
23844
23845        @Override
23846        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23847            synchronized (mPackages) {
23848                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23849                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23850            }
23851        }
23852
23853        @Override
23854        public int getPackageUid(String packageName, int flags, int userId) {
23855            return PackageManagerService.this
23856                    .getPackageUid(packageName, flags, userId);
23857        }
23858
23859        @Override
23860        public ApplicationInfo getApplicationInfo(
23861                String packageName, int flags, int filterCallingUid, int userId) {
23862            return PackageManagerService.this
23863                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23864        }
23865
23866        @Override
23867        public ActivityInfo getActivityInfo(
23868                ComponentName component, int flags, int filterCallingUid, int userId) {
23869            return PackageManagerService.this
23870                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23871        }
23872
23873        @Override
23874        public List<ResolveInfo> queryIntentActivities(
23875                Intent intent, int flags, int filterCallingUid, int userId) {
23876            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23877            return PackageManagerService.this
23878                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23879                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23880        }
23881
23882        @Override
23883        public List<ResolveInfo> queryIntentServices(
23884                Intent intent, int flags, int callingUid, int userId) {
23885            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23886            return PackageManagerService.this
23887                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23888                            false);
23889        }
23890
23891        @Override
23892        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23893                int userId) {
23894            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23895        }
23896
23897        @Override
23898        public ComponentName getDefaultHomeActivity(int userId) {
23899            return PackageManagerService.this.getDefaultHomeActivity(userId);
23900        }
23901
23902        @Override
23903        public void setDeviceAndProfileOwnerPackages(
23904                int deviceOwnerUserId, String deviceOwnerPackage,
23905                SparseArray<String> profileOwnerPackages) {
23906            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23907                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23908        }
23909
23910        @Override
23911        public boolean isPackageDataProtected(int userId, String packageName) {
23912            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23913        }
23914
23915        @Override
23916        public boolean isPackageStateProtected(String packageName, int userId) {
23917            return mProtectedPackages.isPackageStateProtected(userId, packageName);
23918        }
23919
23920        @Override
23921        public boolean isPackageEphemeral(int userId, String packageName) {
23922            synchronized (mPackages) {
23923                final PackageSetting ps = mSettings.mPackages.get(packageName);
23924                return ps != null ? ps.getInstantApp(userId) : false;
23925            }
23926        }
23927
23928        @Override
23929        public boolean wasPackageEverLaunched(String packageName, int userId) {
23930            synchronized (mPackages) {
23931                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23932            }
23933        }
23934
23935        @Override
23936        public void grantRuntimePermission(String packageName, String permName, int userId,
23937                boolean overridePolicy) {
23938            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23939                    permName, packageName, overridePolicy, getCallingUid(), userId,
23940                    mPermissionCallback);
23941        }
23942
23943        @Override
23944        public void revokeRuntimePermission(String packageName, String permName, int userId,
23945                boolean overridePolicy) {
23946            mPermissionManager.revokeRuntimePermission(
23947                    permName, packageName, overridePolicy, getCallingUid(), userId,
23948                    mPermissionCallback);
23949        }
23950
23951        @Override
23952        public String getNameForUid(int uid) {
23953            return PackageManagerService.this.getNameForUid(uid);
23954        }
23955
23956        @Override
23957        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23958                Intent origIntent, String resolvedType, String callingPackage,
23959                Bundle verificationBundle, int userId) {
23960            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23961                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23962                    userId);
23963        }
23964
23965        @Override
23966        public void grantEphemeralAccess(int userId, Intent intent,
23967                int targetAppId, int ephemeralAppId) {
23968            synchronized (mPackages) {
23969                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23970                        targetAppId, ephemeralAppId);
23971            }
23972        }
23973
23974        @Override
23975        public boolean isInstantAppInstallerComponent(ComponentName component) {
23976            synchronized (mPackages) {
23977                return mInstantAppInstallerActivity != null
23978                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23979            }
23980        }
23981
23982        @Override
23983        public void pruneInstantApps() {
23984            mInstantAppRegistry.pruneInstantApps();
23985        }
23986
23987        @Override
23988        public String getSetupWizardPackageName() {
23989            return mSetupWizardPackage;
23990        }
23991
23992        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23993            if (policy != null) {
23994                mExternalSourcesPolicy = policy;
23995            }
23996        }
23997
23998        @Override
23999        public boolean isPackagePersistent(String packageName) {
24000            synchronized (mPackages) {
24001                PackageParser.Package pkg = mPackages.get(packageName);
24002                return pkg != null
24003                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24004                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24005                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24006                        : false;
24007            }
24008        }
24009
24010        @Override
24011        public boolean isLegacySystemApp(Package pkg) {
24012            synchronized (mPackages) {
24013                final PackageSetting ps = (PackageSetting) pkg.mExtras;
24014                return mPromoteSystemApps
24015                        && ps.isSystem()
24016                        && mExistingSystemPackages.contains(ps.name);
24017            }
24018        }
24019
24020        @Override
24021        public List<PackageInfo> getOverlayPackages(int userId) {
24022            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24023            synchronized (mPackages) {
24024                for (PackageParser.Package p : mPackages.values()) {
24025                    if (p.mOverlayTarget != null) {
24026                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24027                        if (pkg != null) {
24028                            overlayPackages.add(pkg);
24029                        }
24030                    }
24031                }
24032            }
24033            return overlayPackages;
24034        }
24035
24036        @Override
24037        public List<String> getTargetPackageNames(int userId) {
24038            List<String> targetPackages = new ArrayList<>();
24039            synchronized (mPackages) {
24040                for (PackageParser.Package p : mPackages.values()) {
24041                    if (p.mOverlayTarget == null) {
24042                        targetPackages.add(p.packageName);
24043                    }
24044                }
24045            }
24046            return targetPackages;
24047        }
24048
24049        @Override
24050        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24051                @Nullable List<String> overlayPackageNames) {
24052            synchronized (mPackages) {
24053                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24054                    Slog.e(TAG, "failed to find package " + targetPackageName);
24055                    return false;
24056                }
24057                ArrayList<String> overlayPaths = null;
24058                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24059                    final int N = overlayPackageNames.size();
24060                    overlayPaths = new ArrayList<>(N);
24061                    for (int i = 0; i < N; i++) {
24062                        final String packageName = overlayPackageNames.get(i);
24063                        final PackageParser.Package pkg = mPackages.get(packageName);
24064                        if (pkg == null) {
24065                            Slog.e(TAG, "failed to find package " + packageName);
24066                            return false;
24067                        }
24068                        overlayPaths.add(pkg.baseCodePath);
24069                    }
24070                }
24071
24072                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24073                ps.setOverlayPaths(overlayPaths, userId);
24074                return true;
24075            }
24076        }
24077
24078        @Override
24079        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24080                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24081            return resolveIntentInternal(
24082                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24083        }
24084
24085        @Override
24086        public ResolveInfo resolveService(Intent intent, String resolvedType,
24087                int flags, int userId, int callingUid) {
24088            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24089        }
24090
24091        @Override
24092        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24093            return PackageManagerService.this.resolveContentProviderInternal(
24094                    name, flags, userId);
24095        }
24096
24097        @Override
24098        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24099            synchronized (mPackages) {
24100                mIsolatedOwners.put(isolatedUid, ownerUid);
24101            }
24102        }
24103
24104        @Override
24105        public void removeIsolatedUid(int isolatedUid) {
24106            synchronized (mPackages) {
24107                mIsolatedOwners.delete(isolatedUid);
24108            }
24109        }
24110
24111        @Override
24112        public int getUidTargetSdkVersion(int uid) {
24113            synchronized (mPackages) {
24114                return getUidTargetSdkVersionLockedLPr(uid);
24115            }
24116        }
24117
24118        @Override
24119        public int getPackageTargetSdkVersion(String packageName) {
24120            synchronized (mPackages) {
24121                return getPackageTargetSdkVersionLockedLPr(packageName);
24122            }
24123        }
24124
24125        @Override
24126        public boolean canAccessInstantApps(int callingUid, int userId) {
24127            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24128        }
24129
24130        @Override
24131        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24132            synchronized (mPackages) {
24133                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24134                return !PackageManagerService.this.filterAppAccessLPr(
24135                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24136            }
24137        }
24138
24139        @Override
24140        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24141            synchronized (mPackages) {
24142                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24143            }
24144        }
24145
24146        @Override
24147        public void notifyPackageUse(String packageName, int reason) {
24148            synchronized (mPackages) {
24149                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24150            }
24151        }
24152    }
24153
24154    @Override
24155    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24156        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24157        synchronized (mPackages) {
24158            final long identity = Binder.clearCallingIdentity();
24159            try {
24160                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24161                        packageNames, userId);
24162            } finally {
24163                Binder.restoreCallingIdentity(identity);
24164            }
24165        }
24166    }
24167
24168    @Override
24169    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24170        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24171        synchronized (mPackages) {
24172            final long identity = Binder.clearCallingIdentity();
24173            try {
24174                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24175                        packageNames, userId);
24176            } finally {
24177                Binder.restoreCallingIdentity(identity);
24178            }
24179        }
24180    }
24181
24182    @Override
24183    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24184            String[] packageNames, int userId) {
24185        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24186        synchronized (mPackages) {
24187            Binder.withCleanCallingIdentity( () -> {
24188                mDefaultPermissionPolicy.
24189                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24190                                packageNames, userId);
24191            });
24192        }
24193    }
24194
24195    @Override
24196    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24197            String[] packageNames, int userId) {
24198        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24199        synchronized (mPackages) {
24200            Binder.withCleanCallingIdentity( () -> {
24201                mDefaultPermissionPolicy.
24202                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24203                                packageNames, userId);
24204            });
24205        }
24206    }
24207
24208    @Override
24209    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24210        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24211        synchronized (mPackages) {
24212            final long identity = Binder.clearCallingIdentity();
24213            try {
24214                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24215                        packageName, userId);
24216            } finally {
24217                Binder.restoreCallingIdentity(identity);
24218            }
24219        }
24220    }
24221
24222    @Override
24223    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24224        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24225        synchronized (mPackages) {
24226            final long identity = Binder.clearCallingIdentity();
24227            try {
24228                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24229            } finally {
24230                Binder.restoreCallingIdentity(identity);
24231            }
24232        }
24233    }
24234
24235    private static void enforceSystemOrPhoneCaller(String tag) {
24236        int callingUid = Binder.getCallingUid();
24237        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24238            throw new SecurityException(
24239                    "Cannot call " + tag + " from UID " + callingUid);
24240        }
24241    }
24242
24243    boolean isHistoricalPackageUsageAvailable() {
24244        return mPackageUsage.isHistoricalPackageUsageAvailable();
24245    }
24246
24247    /**
24248     * Return a <b>copy</b> of the collection of packages known to the package manager.
24249     * @return A copy of the values of mPackages.
24250     */
24251    Collection<PackageParser.Package> getPackages() {
24252        synchronized (mPackages) {
24253            return new ArrayList<>(mPackages.values());
24254        }
24255    }
24256
24257    /**
24258     * Logs process start information (including base APK hash) to the security log.
24259     * @hide
24260     */
24261    @Override
24262    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24263            String apkFile, int pid) {
24264        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24265            return;
24266        }
24267        if (!SecurityLog.isLoggingEnabled()) {
24268            return;
24269        }
24270        Bundle data = new Bundle();
24271        data.putLong("startTimestamp", System.currentTimeMillis());
24272        data.putString("processName", processName);
24273        data.putInt("uid", uid);
24274        data.putString("seinfo", seinfo);
24275        data.putString("apkFile", apkFile);
24276        data.putInt("pid", pid);
24277        Message msg = mProcessLoggingHandler.obtainMessage(
24278                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24279        msg.setData(data);
24280        mProcessLoggingHandler.sendMessage(msg);
24281    }
24282
24283    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24284        return mCompilerStats.getPackageStats(pkgName);
24285    }
24286
24287    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24288        return getOrCreateCompilerPackageStats(pkg.packageName);
24289    }
24290
24291    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24292        return mCompilerStats.getOrCreatePackageStats(pkgName);
24293    }
24294
24295    public void deleteCompilerPackageStats(String pkgName) {
24296        mCompilerStats.deletePackageStats(pkgName);
24297    }
24298
24299    @Override
24300    public int getInstallReason(String packageName, int userId) {
24301        final int callingUid = Binder.getCallingUid();
24302        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24303                true /* requireFullPermission */, false /* checkShell */,
24304                "get install reason");
24305        synchronized (mPackages) {
24306            final PackageSetting ps = mSettings.mPackages.get(packageName);
24307            if (filterAppAccessLPr(ps, callingUid, userId)) {
24308                return PackageManager.INSTALL_REASON_UNKNOWN;
24309            }
24310            if (ps != null) {
24311                return ps.getInstallReason(userId);
24312            }
24313        }
24314        return PackageManager.INSTALL_REASON_UNKNOWN;
24315    }
24316
24317    @Override
24318    public boolean canRequestPackageInstalls(String packageName, int userId) {
24319        return canRequestPackageInstallsInternal(packageName, 0, userId,
24320                true /* throwIfPermNotDeclared*/);
24321    }
24322
24323    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24324            boolean throwIfPermNotDeclared) {
24325        int callingUid = Binder.getCallingUid();
24326        int uid = getPackageUid(packageName, 0, userId);
24327        if (callingUid != uid && callingUid != Process.ROOT_UID
24328                && callingUid != Process.SYSTEM_UID) {
24329            throw new SecurityException(
24330                    "Caller uid " + callingUid + " does not own package " + packageName);
24331        }
24332        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24333        if (info == null) {
24334            return false;
24335        }
24336        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24337            return false;
24338        }
24339        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24340        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24341        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24342            if (throwIfPermNotDeclared) {
24343                throw new SecurityException("Need to declare " + appOpPermission
24344                        + " to call this api");
24345            } else {
24346                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24347                return false;
24348            }
24349        }
24350        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24351            return false;
24352        }
24353        if (mExternalSourcesPolicy != null) {
24354            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24355            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24356                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24357            }
24358        }
24359        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24360    }
24361
24362    @Override
24363    public ComponentName getInstantAppResolverSettingsComponent() {
24364        return mInstantAppResolverSettingsComponent;
24365    }
24366
24367    @Override
24368    public ComponentName getInstantAppInstallerComponent() {
24369        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24370            return null;
24371        }
24372        return mInstantAppInstallerActivity == null
24373                ? null : mInstantAppInstallerActivity.getComponentName();
24374    }
24375
24376    @Override
24377    public String getInstantAppAndroidId(String packageName, int userId) {
24378        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24379                "getInstantAppAndroidId");
24380        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24381                true /* requireFullPermission */, false /* checkShell */,
24382                "getInstantAppAndroidId");
24383        // Make sure the target is an Instant App.
24384        if (!isInstantApp(packageName, userId)) {
24385            return null;
24386        }
24387        synchronized (mPackages) {
24388            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24389        }
24390    }
24391
24392    boolean canHaveOatDir(String packageName) {
24393        synchronized (mPackages) {
24394            PackageParser.Package p = mPackages.get(packageName);
24395            if (p == null) {
24396                return false;
24397            }
24398            return p.canHaveOatDir();
24399        }
24400    }
24401
24402    private String getOatDir(PackageParser.Package pkg) {
24403        if (!pkg.canHaveOatDir()) {
24404            return null;
24405        }
24406        File codePath = new File(pkg.codePath);
24407        if (codePath.isDirectory()) {
24408            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24409        }
24410        return null;
24411    }
24412
24413    void deleteOatArtifactsOfPackage(String packageName) {
24414        final String[] instructionSets;
24415        final List<String> codePaths;
24416        final String oatDir;
24417        final PackageParser.Package pkg;
24418        synchronized (mPackages) {
24419            pkg = mPackages.get(packageName);
24420        }
24421        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24422        codePaths = pkg.getAllCodePaths();
24423        oatDir = getOatDir(pkg);
24424
24425        for (String codePath : codePaths) {
24426            for (String isa : instructionSets) {
24427                try {
24428                    mInstaller.deleteOdex(codePath, isa, oatDir);
24429                } catch (InstallerException e) {
24430                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24431                }
24432            }
24433        }
24434    }
24435
24436    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24437        Set<String> unusedPackages = new HashSet<>();
24438        long currentTimeInMillis = System.currentTimeMillis();
24439        synchronized (mPackages) {
24440            for (PackageParser.Package pkg : mPackages.values()) {
24441                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24442                if (ps == null) {
24443                    continue;
24444                }
24445                PackageDexUsage.PackageUseInfo packageUseInfo =
24446                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24447                if (PackageManagerServiceUtils
24448                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24449                                downgradeTimeThresholdMillis, packageUseInfo,
24450                                pkg.getLatestPackageUseTimeInMills(),
24451                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24452                    unusedPackages.add(pkg.packageName);
24453                }
24454            }
24455        }
24456        return unusedPackages;
24457    }
24458
24459    @Override
24460    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24461            int userId) {
24462        final int callingUid = Binder.getCallingUid();
24463        final int callingAppId = UserHandle.getAppId(callingUid);
24464
24465        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24466                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24467
24468        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24469                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24470            throw new SecurityException("Caller must have the "
24471                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24472        }
24473
24474        synchronized(mPackages) {
24475            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24476            scheduleWritePackageRestrictionsLocked(userId);
24477        }
24478    }
24479
24480    @Nullable
24481    @Override
24482    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24483        final int callingUid = Binder.getCallingUid();
24484        final int callingAppId = UserHandle.getAppId(callingUid);
24485
24486        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24487                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24488
24489        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24490                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24491            throw new SecurityException("Caller must have the "
24492                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24493        }
24494
24495        synchronized(mPackages) {
24496            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24497        }
24498    }
24499
24500    @Override
24501    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24502        final int callingUid = Binder.getCallingUid();
24503        final int callingAppId = UserHandle.getAppId(callingUid);
24504
24505        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24506                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24507
24508        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24509                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24510            throw new SecurityException("Caller must have the "
24511                    + MANAGE_DEVICE_ADMINS + " permission.");
24512        }
24513
24514        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24515    }
24516}
24517
24518interface PackageSender {
24519    /**
24520     * @param userIds User IDs where the action occurred on a full application
24521     * @param instantUserIds User IDs where the action occurred on an instant application
24522     */
24523    void sendPackageBroadcast(final String action, final String pkg,
24524        final Bundle extras, final int flags, final String targetPkg,
24525        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24526    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24527        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24528    void notifyPackageAdded(String packageName);
24529    void notifyPackageRemoved(String packageName);
24530}
24531