PackageManagerService.java revision aa1a911d9a0f797748b001c41bd8df2f517b318c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
28import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
34import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
42import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
88import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
89import static android.system.OsConstants.O_CREAT;
90import static android.system.OsConstants.O_RDWR;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendElement;
96import static com.android.internal.util.ArrayUtils.appendInt;
97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115
116import android.Manifest;
117import android.annotation.IntDef;
118import android.annotation.NonNull;
119import android.annotation.Nullable;
120import android.annotation.UserIdInt;
121import android.app.ActivityManager;
122import android.app.ActivityManagerInternal;
123import android.app.AppOpsManager;
124import android.app.IActivityManager;
125import android.app.ResourcesManager;
126import android.app.admin.IDevicePolicyManager;
127import android.app.admin.SecurityLog;
128import android.app.backup.IBackupManager;
129import android.content.BroadcastReceiver;
130import android.content.ComponentName;
131import android.content.ContentResolver;
132import android.content.Context;
133import android.content.IIntentReceiver;
134import android.content.Intent;
135import android.content.IntentFilter;
136import android.content.IntentSender;
137import android.content.IntentSender.SendIntentException;
138import android.content.ServiceConnection;
139import android.content.pm.ActivityInfo;
140import android.content.pm.ApplicationInfo;
141import android.content.pm.AppsQueryHelper;
142import android.content.pm.AuxiliaryResolveInfo;
143import android.content.pm.ChangedPackages;
144import android.content.pm.ComponentInfo;
145import android.content.pm.FallbackCategoryProvider;
146import android.content.pm.FeatureInfo;
147import android.content.pm.IDexModuleRegisterCallback;
148import android.content.pm.IOnPermissionsChangeListener;
149import android.content.pm.IPackageDataObserver;
150import android.content.pm.IPackageDeleteObserver;
151import android.content.pm.IPackageDeleteObserver2;
152import android.content.pm.IPackageInstallObserver2;
153import android.content.pm.IPackageInstaller;
154import android.content.pm.IPackageManager;
155import android.content.pm.IPackageManagerNative;
156import android.content.pm.IPackageMoveObserver;
157import android.content.pm.IPackageStatsObserver;
158import android.content.pm.InstantAppInfo;
159import android.content.pm.InstantAppRequest;
160import android.content.pm.InstantAppResolveInfo;
161import android.content.pm.InstrumentationInfo;
162import android.content.pm.IntentFilterVerificationInfo;
163import android.content.pm.KeySet;
164import android.content.pm.PackageCleanItem;
165import android.content.pm.PackageInfo;
166import android.content.pm.PackageInfoLite;
167import android.content.pm.PackageInstaller;
168import android.content.pm.PackageList;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
171import android.content.pm.PackageManagerInternal;
172import android.content.pm.PackageManagerInternal.PackageListObserver;
173import android.content.pm.PackageParser;
174import android.content.pm.PackageParser.ActivityIntentInfo;
175import android.content.pm.PackageParser.Package;
176import android.content.pm.PackageParser.PackageLite;
177import android.content.pm.PackageParser.PackageParserException;
178import android.content.pm.PackageParser.ParseFlags;
179import android.content.pm.PackageParser.ServiceIntentInfo;
180import android.content.pm.PackageParser.SigningDetails;
181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182import android.content.pm.PackageStats;
183import android.content.pm.PackageUserState;
184import android.content.pm.ParceledListSlice;
185import android.content.pm.PermissionGroupInfo;
186import android.content.pm.PermissionInfo;
187import android.content.pm.ProviderInfo;
188import android.content.pm.ResolveInfo;
189import android.content.pm.SELinuxUtil;
190import android.content.pm.ServiceInfo;
191import android.content.pm.SharedLibraryInfo;
192import android.content.pm.Signature;
193import android.content.pm.UserInfo;
194import android.content.pm.VerifierDeviceIdentity;
195import android.content.pm.VerifierInfo;
196import android.content.pm.VersionedPackage;
197import android.content.pm.dex.ArtManager;
198import android.content.pm.dex.DexMetadataHelper;
199import android.content.pm.dex.IArtManager;
200import android.content.res.Resources;
201import android.database.ContentObserver;
202import android.graphics.Bitmap;
203import android.hardware.display.DisplayManager;
204import android.net.Uri;
205import android.os.Binder;
206import android.os.Build;
207import android.os.Bundle;
208import android.os.Debug;
209import android.os.Environment;
210import android.os.Environment.UserEnvironment;
211import android.os.FileUtils;
212import android.os.Handler;
213import android.os.IBinder;
214import android.os.Looper;
215import android.os.Message;
216import android.os.Parcel;
217import android.os.ParcelFileDescriptor;
218import android.os.PatternMatcher;
219import android.os.PersistableBundle;
220import android.os.Process;
221import android.os.RemoteCallbackList;
222import android.os.RemoteException;
223import android.os.ResultReceiver;
224import android.os.SELinux;
225import android.os.ServiceManager;
226import android.os.ShellCallback;
227import android.os.SystemClock;
228import android.os.SystemProperties;
229import android.os.Trace;
230import android.os.UserHandle;
231import android.os.UserManager;
232import android.os.UserManagerInternal;
233import android.os.storage.IStorageManager;
234import android.os.storage.StorageEventListener;
235import android.os.storage.StorageManager;
236import android.os.storage.StorageManagerInternal;
237import android.os.storage.VolumeInfo;
238import android.os.storage.VolumeRecord;
239import android.provider.Settings.Global;
240import android.provider.Settings.Secure;
241import android.security.KeyStore;
242import android.security.SystemKeyStore;
243import android.service.pm.PackageServiceDumpProto;
244import android.system.ErrnoException;
245import android.system.Os;
246import android.text.TextUtils;
247import android.text.format.DateUtils;
248import android.util.ArrayMap;
249import android.util.ArraySet;
250import android.util.Base64;
251import android.util.ByteStringUtils;
252import android.util.DisplayMetrics;
253import android.util.EventLog;
254import android.util.ExceptionUtils;
255import android.util.Log;
256import android.util.LogPrinter;
257import android.util.LongSparseArray;
258import android.util.LongSparseLongArray;
259import android.util.MathUtils;
260import android.util.PackageUtils;
261import android.util.Pair;
262import android.util.PrintStreamPrinter;
263import android.util.Slog;
264import android.util.SparseArray;
265import android.util.SparseBooleanArray;
266import android.util.SparseIntArray;
267import android.util.TimingsTraceLog;
268import android.util.Xml;
269import android.util.jar.StrictJarFile;
270import android.util.proto.ProtoOutputStream;
271import android.view.Display;
272
273import com.android.internal.R;
274import com.android.internal.annotations.GuardedBy;
275import com.android.internal.app.IMediaContainerService;
276import com.android.internal.app.ResolverActivity;
277import com.android.internal.app.SuspendedAppActivity;
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 = true;
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                                return;
1527                            }
1528                            mPendingInstalls.clear();
1529                        } else {
1530                            Slog.w(TAG, "Waiting to connect to media container service");
1531                        }
1532                    } else if (mPendingInstalls.size() > 0) {
1533                        HandlerParams params = mPendingInstalls.get(0);
1534                        if (params != null) {
1535                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1536                                    System.identityHashCode(params));
1537                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1538                            if (params.startCopy()) {
1539                                // We are done...  look for more work or to
1540                                // go idle.
1541                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                        "Checking for more work or unbind...");
1543                                // Delete pending install
1544                                if (mPendingInstalls.size() > 0) {
1545                                    mPendingInstalls.remove(0);
1546                                }
1547                                if (mPendingInstalls.size() == 0) {
1548                                    if (mBound) {
1549                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1550                                                "Posting delayed MCS_UNBIND");
1551                                        removeMessages(MCS_UNBIND);
1552                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1553                                        // Unbind after a little delay, to avoid
1554                                        // continual thrashing.
1555                                        sendMessageDelayed(ubmsg, 10000);
1556                                    }
1557                                } else {
1558                                    // There are more pending requests in queue.
1559                                    // Just post MCS_BOUND message to trigger processing
1560                                    // of next pending install.
1561                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1562                                            "Posting MCS_BOUND for next work");
1563                                    mHandler.sendEmptyMessage(MCS_BOUND);
1564                                }
1565                            }
1566                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1567                        }
1568                    } else {
1569                        // Should never happen ideally.
1570                        Slog.w(TAG, "Empty queue");
1571                    }
1572                    break;
1573                }
1574                case MCS_RECONNECT: {
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1576                    if (mPendingInstalls.size() > 0) {
1577                        if (mBound) {
1578                            disconnectService();
1579                        }
1580                        if (!connectToService()) {
1581                            Slog.e(TAG, "Failed to bind to media container service");
1582                            for (HandlerParams params : mPendingInstalls) {
1583                                // Indicate service bind error
1584                                params.serviceError();
1585                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                                        System.identityHashCode(params));
1587                            }
1588                            mPendingInstalls.clear();
1589                        }
1590                    }
1591                    break;
1592                }
1593                case MCS_UNBIND: {
1594                    // If there is no actual work left, then time to unbind.
1595                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1596
1597                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1598                        if (mBound) {
1599                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1600
1601                            disconnectService();
1602                        }
1603                    } else if (mPendingInstalls.size() > 0) {
1604                        // There are more pending requests in queue.
1605                        // Just post MCS_BOUND message to trigger processing
1606                        // of next pending install.
1607                        mHandler.sendEmptyMessage(MCS_BOUND);
1608                    }
1609
1610                    break;
1611                }
1612                case MCS_GIVE_UP: {
1613                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1614                    HandlerParams params = mPendingInstalls.remove(0);
1615                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1616                            System.identityHashCode(params));
1617                    break;
1618                }
1619                case SEND_PENDING_BROADCAST: {
1620                    String packages[];
1621                    ArrayList<String> components[];
1622                    int size = 0;
1623                    int uids[];
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1625                    synchronized (mPackages) {
1626                        if (mPendingBroadcasts == null) {
1627                            return;
1628                        }
1629                        size = mPendingBroadcasts.size();
1630                        if (size <= 0) {
1631                            // Nothing to be done. Just return
1632                            return;
1633                        }
1634                        packages = new String[size];
1635                        components = new ArrayList[size];
1636                        uids = new int[size];
1637                        int i = 0;  // filling out the above arrays
1638
1639                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1640                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1641                            Iterator<Map.Entry<String, ArrayList<String>>> it
1642                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1643                                            .entrySet().iterator();
1644                            while (it.hasNext() && i < size) {
1645                                Map.Entry<String, ArrayList<String>> ent = it.next();
1646                                packages[i] = ent.getKey();
1647                                components[i] = ent.getValue();
1648                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1649                                uids[i] = (ps != null)
1650                                        ? UserHandle.getUid(packageUserId, ps.appId)
1651                                        : -1;
1652                                i++;
1653                            }
1654                        }
1655                        size = i;
1656                        mPendingBroadcasts.clear();
1657                    }
1658                    // Send broadcasts
1659                    for (int i = 0; i < size; i++) {
1660                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    break;
1664                }
1665                case START_CLEANING_PACKAGE: {
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1667                    final String packageName = (String)msg.obj;
1668                    final int userId = msg.arg1;
1669                    final boolean andCode = msg.arg2 != 0;
1670                    synchronized (mPackages) {
1671                        if (userId == UserHandle.USER_ALL) {
1672                            int[] users = sUserManager.getUserIds();
1673                            for (int user : users) {
1674                                mSettings.addPackageToCleanLPw(
1675                                        new PackageCleanItem(user, packageName, andCode));
1676                            }
1677                        } else {
1678                            mSettings.addPackageToCleanLPw(
1679                                    new PackageCleanItem(userId, packageName, andCode));
1680                        }
1681                    }
1682                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1683                    startCleaningPackages();
1684                } break;
1685                case POST_INSTALL: {
1686                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1687
1688                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1689                    final boolean didRestore = (msg.arg2 != 0);
1690                    mRunningInstalls.delete(msg.arg1);
1691
1692                    if (data != null) {
1693                        InstallArgs args = data.args;
1694                        PackageInstalledInfo parentRes = data.res;
1695
1696                        final boolean grantPermissions = (args.installFlags
1697                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1698                        final boolean killApp = (args.installFlags
1699                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1700                        final boolean virtualPreload = ((args.installFlags
1701                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1702                        final String[] grantedPermissions = args.installGrantPermissions;
1703
1704                        // Handle the parent package
1705                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1706                                virtualPreload, grantedPermissions, didRestore,
1707                                args.installerPackageName, args.observer);
1708
1709                        // Handle the child packages
1710                        final int childCount = (parentRes.addedChildPackages != null)
1711                                ? parentRes.addedChildPackages.size() : 0;
1712                        for (int i = 0; i < childCount; i++) {
1713                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1714                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1715                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1716                                    args.installerPackageName, args.observer);
1717                        }
1718
1719                        // Log tracing if needed
1720                        if (args.traceMethod != null) {
1721                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1722                                    args.traceCookie);
1723                        }
1724                    } else {
1725                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1726                    }
1727
1728                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1729                } break;
1730                case WRITE_SETTINGS: {
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1732                    synchronized (mPackages) {
1733                        removeMessages(WRITE_SETTINGS);
1734                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1735                        mSettings.writeLPr();
1736                        mDirtyUsers.clear();
1737                    }
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                } break;
1740                case WRITE_PACKAGE_RESTRICTIONS: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1744                        for (int userId : mDirtyUsers) {
1745                            mSettings.writePackageRestrictionsLPr(userId);
1746                        }
1747                        mDirtyUsers.clear();
1748                    }
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1750                } break;
1751                case WRITE_PACKAGE_LIST: {
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1753                    synchronized (mPackages) {
1754                        removeMessages(WRITE_PACKAGE_LIST);
1755                        mSettings.writePackageListLPr(msg.arg1);
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case CHECK_PENDING_VERIFICATION: {
1760                    final int verificationId = msg.arg1;
1761                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1762
1763                    if ((state != null) && !state.timeoutExtended()) {
1764                        final InstallArgs args = state.getInstallArgs();
1765                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1766
1767                        Slog.i(TAG, "Verification timed out for " + originUri);
1768                        mPendingVerification.remove(verificationId);
1769
1770                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1771
1772                        final UserHandle user = args.getUser();
1773                        if (getDefaultVerificationResponse(user)
1774                                == PackageManager.VERIFICATION_ALLOW) {
1775                            Slog.i(TAG, "Continuing with installation of " + originUri);
1776                            state.setVerifierResponse(Binder.getCallingUid(),
1777                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1778                            broadcastPackageVerified(verificationId, originUri,
1779                                    PackageManager.VERIFICATION_ALLOW, user);
1780                            try {
1781                                ret = args.copyApk(mContainerService, true);
1782                            } catch (RemoteException e) {
1783                                Slog.e(TAG, "Could not contact the ContainerService");
1784                            }
1785                        } else {
1786                            broadcastPackageVerified(verificationId, originUri,
1787                                    PackageManager.VERIFICATION_REJECT, user);
1788                        }
1789
1790                        Trace.asyncTraceEnd(
1791                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1792
1793                        processPendingInstall(args, ret);
1794                        mHandler.sendEmptyMessage(MCS_UNBIND);
1795                    }
1796                    break;
1797                }
1798                case PACKAGE_VERIFIED: {
1799                    final int verificationId = msg.arg1;
1800
1801                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1802                    if (state == null) {
1803                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1804                        break;
1805                    }
1806
1807                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1808
1809                    state.setVerifierResponse(response.callerUid, response.code);
1810
1811                    if (state.isVerificationComplete()) {
1812                        mPendingVerification.remove(verificationId);
1813
1814                        final InstallArgs args = state.getInstallArgs();
1815                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1816
1817                        int ret;
1818                        if (state.isInstallAllowed()) {
1819                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1820                            broadcastPackageVerified(verificationId, originUri,
1821                                    response.code, state.getInstallArgs().getUser());
1822                            try {
1823                                ret = args.copyApk(mContainerService, true);
1824                            } catch (RemoteException e) {
1825                                Slog.e(TAG, "Could not contact the ContainerService");
1826                            }
1827                        } else {
1828                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1829                        }
1830
1831                        Trace.asyncTraceEnd(
1832                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1833
1834                        processPendingInstall(args, ret);
1835                        mHandler.sendEmptyMessage(MCS_UNBIND);
1836                    }
1837
1838                    break;
1839                }
1840                case START_INTENT_FILTER_VERIFICATIONS: {
1841                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1842                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1843                            params.replacing, params.pkg);
1844                    break;
1845                }
1846                case INTENT_FILTER_VERIFIED: {
1847                    final int verificationId = msg.arg1;
1848
1849                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1850                            verificationId);
1851                    if (state == null) {
1852                        Slog.w(TAG, "Invalid IntentFilter verification token "
1853                                + verificationId + " received");
1854                        break;
1855                    }
1856
1857                    final int userId = state.getUserId();
1858
1859                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1860                            "Processing IntentFilter verification with token:"
1861                            + verificationId + " and userId:" + userId);
1862
1863                    final IntentFilterVerificationResponse response =
1864                            (IntentFilterVerificationResponse) msg.obj;
1865
1866                    state.setVerifierResponse(response.callerUid, response.code);
1867
1868                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1869                            "IntentFilter verification with token:" + verificationId
1870                            + " and userId:" + userId
1871                            + " is settings verifier response with response code:"
1872                            + response.code);
1873
1874                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1875                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1876                                + response.getFailedDomainsString());
1877                    }
1878
1879                    if (state.isVerificationComplete()) {
1880                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1881                    } else {
1882                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1883                                "IntentFilter verification with token:" + verificationId
1884                                + " was not said to be complete");
1885                    }
1886
1887                    break;
1888                }
1889                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1890                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1891                            mInstantAppResolverConnection,
1892                            (InstantAppRequest) msg.obj,
1893                            mInstantAppInstallerActivity,
1894                            mHandler);
1895                }
1896            }
1897        }
1898    }
1899
1900    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1901        @Override
1902        public void onGidsChanged(int appId, int userId) {
1903            mHandler.post(new Runnable() {
1904                @Override
1905                public void run() {
1906                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1907                }
1908            });
1909        }
1910        @Override
1911        public void onPermissionGranted(int uid, int userId) {
1912            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1913
1914            // Not critical; if this is lost, the application has to request again.
1915            synchronized (mPackages) {
1916                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1917            }
1918        }
1919        @Override
1920        public void onInstallPermissionGranted() {
1921            synchronized (mPackages) {
1922                scheduleWriteSettingsLocked();
1923            }
1924        }
1925        @Override
1926        public void onPermissionRevoked(int uid, int userId) {
1927            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1928
1929            synchronized (mPackages) {
1930                // Critical; after this call the application should never have the permission
1931                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1932            }
1933
1934            final int appId = UserHandle.getAppId(uid);
1935            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1936        }
1937        @Override
1938        public void onInstallPermissionRevoked() {
1939            synchronized (mPackages) {
1940                scheduleWriteSettingsLocked();
1941            }
1942        }
1943        @Override
1944        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1945            synchronized (mPackages) {
1946                for (int userId : updatedUserIds) {
1947                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1948                }
1949            }
1950        }
1951        @Override
1952        public void onInstallPermissionUpdated() {
1953            synchronized (mPackages) {
1954                scheduleWriteSettingsLocked();
1955            }
1956        }
1957        @Override
1958        public void onPermissionRemoved() {
1959            synchronized (mPackages) {
1960                mSettings.writeLPr();
1961            }
1962        }
1963    };
1964
1965    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1966            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1967            boolean launchedForRestore, String installerPackage,
1968            IPackageInstallObserver2 installObserver) {
1969        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1970            // Send the removed broadcasts
1971            if (res.removedInfo != null) {
1972                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1973            }
1974
1975            // Now that we successfully installed the package, grant runtime
1976            // permissions if requested before broadcasting the install. Also
1977            // for legacy apps in permission review mode we clear the permission
1978            // review flag which is used to emulate runtime permissions for
1979            // legacy apps.
1980            if (grantPermissions) {
1981                final int callingUid = Binder.getCallingUid();
1982                mPermissionManager.grantRequestedRuntimePermissions(
1983                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1984                        mPermissionCallback);
1985            }
1986
1987            final boolean update = res.removedInfo != null
1988                    && res.removedInfo.removedPackage != null;
1989            final String installerPackageName =
1990                    res.installerPackageName != null
1991                            ? res.installerPackageName
1992                            : res.removedInfo != null
1993                                    ? res.removedInfo.installerPackageName
1994                                    : null;
1995
1996            // If this is the first time we have child packages for a disabled privileged
1997            // app that had no children, we grant requested runtime permissions to the new
1998            // children if the parent on the system image had them already granted.
1999            if (res.pkg.parentPackage != null) {
2000                final int callingUid = Binder.getCallingUid();
2001                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2002                        res.pkg, callingUid, mPermissionCallback);
2003            }
2004
2005            synchronized (mPackages) {
2006                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2007            }
2008
2009            final String packageName = res.pkg.applicationInfo.packageName;
2010
2011            // Determine the set of users who are adding this package for
2012            // the first time vs. those who are seeing an update.
2013            int[] firstUserIds = EMPTY_INT_ARRAY;
2014            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2015            int[] updateUserIds = EMPTY_INT_ARRAY;
2016            int[] instantUserIds = EMPTY_INT_ARRAY;
2017            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2018            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2019            for (int newUser : res.newUsers) {
2020                final boolean isInstantApp = ps.getInstantApp(newUser);
2021                if (allNewUsers) {
2022                    if (isInstantApp) {
2023                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2024                    } else {
2025                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2026                    }
2027                    continue;
2028                }
2029                boolean isNew = true;
2030                for (int origUser : res.origUsers) {
2031                    if (origUser == newUser) {
2032                        isNew = false;
2033                        break;
2034                    }
2035                }
2036                if (isNew) {
2037                    if (isInstantApp) {
2038                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2039                    } else {
2040                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2041                    }
2042                } else {
2043                    if (isInstantApp) {
2044                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2045                    } else {
2046                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2047                    }
2048                }
2049            }
2050
2051            // Send installed broadcasts if the package is not a static shared lib.
2052            if (res.pkg.staticSharedLibName == null) {
2053                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2054
2055                // Send added for users that see the package for the first time
2056                // sendPackageAddedForNewUsers also deals with system apps
2057                int appId = UserHandle.getAppId(res.uid);
2058                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2059                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2060                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2061
2062                // Send added for users that don't see the package for the first time
2063                Bundle extras = new Bundle(1);
2064                extras.putInt(Intent.EXTRA_UID, res.uid);
2065                if (update) {
2066                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2067                }
2068                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2069                        extras, 0 /*flags*/,
2070                        null /*targetPackage*/, null /*finishedReceiver*/,
2071                        updateUserIds, instantUserIds);
2072                if (installerPackageName != null) {
2073                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2074                            extras, 0 /*flags*/,
2075                            installerPackageName, null /*finishedReceiver*/,
2076                            updateUserIds, instantUserIds);
2077                }
2078
2079                // Send replaced for users that don't see the package for the first time
2080                if (update) {
2081                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2082                            packageName, extras, 0 /*flags*/,
2083                            null /*targetPackage*/, null /*finishedReceiver*/,
2084                            updateUserIds, instantUserIds);
2085                    if (installerPackageName != null) {
2086                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2087                                extras, 0 /*flags*/,
2088                                installerPackageName, null /*finishedReceiver*/,
2089                                updateUserIds, instantUserIds);
2090                    }
2091                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2092                            null /*package*/, null /*extras*/, 0 /*flags*/,
2093                            packageName /*targetPackage*/,
2094                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2095                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2096                    // First-install and we did a restore, so we're responsible for the
2097                    // first-launch broadcast.
2098                    if (DEBUG_BACKUP) {
2099                        Slog.i(TAG, "Post-restore of " + packageName
2100                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2101                    }
2102                    sendFirstLaunchBroadcast(packageName, installerPackage,
2103                            firstUserIds, firstInstantUserIds);
2104                }
2105
2106                // Send broadcast package appeared if forward locked/external for all users
2107                // treat asec-hosted packages like removable media on upgrade
2108                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2109                    if (DEBUG_INSTALL) {
2110                        Slog.i(TAG, "upgrading pkg " + res.pkg
2111                                + " is ASEC-hosted -> AVAILABLE");
2112                    }
2113                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2114                    ArrayList<String> pkgList = new ArrayList<>(1);
2115                    pkgList.add(packageName);
2116                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2117                }
2118            }
2119
2120            // Work that needs to happen on first install within each user
2121            if (firstUserIds != null && firstUserIds.length > 0) {
2122                synchronized (mPackages) {
2123                    for (int userId : firstUserIds) {
2124                        // If this app is a browser and it's newly-installed for some
2125                        // users, clear any default-browser state in those users. The
2126                        // app's nature doesn't depend on the user, so we can just check
2127                        // its browser nature in any user and generalize.
2128                        if (packageIsBrowser(packageName, userId)) {
2129                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2130                        }
2131
2132                        // We may also need to apply pending (restored) runtime
2133                        // permission grants within these users.
2134                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2135                    }
2136                }
2137            }
2138
2139            if (allNewUsers && !update) {
2140                notifyPackageAdded(packageName);
2141            }
2142
2143            // Log current value of "unknown sources" setting
2144            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2145                    getUnknownSourcesSettings());
2146
2147            // Remove the replaced package's older resources safely now
2148            // We delete after a gc for applications  on sdcard.
2149            if (res.removedInfo != null && res.removedInfo.args != null) {
2150                Runtime.getRuntime().gc();
2151                synchronized (mInstallLock) {
2152                    res.removedInfo.args.doPostDeleteLI(true);
2153                }
2154            } else {
2155                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2156                // and not block here.
2157                VMRuntime.getRuntime().requestConcurrentGC();
2158            }
2159
2160            // Notify DexManager that the package was installed for new users.
2161            // The updated users should already be indexed and the package code paths
2162            // should not change.
2163            // Don't notify the manager for ephemeral apps as they are not expected to
2164            // survive long enough to benefit of background optimizations.
2165            for (int userId : firstUserIds) {
2166                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2167                // There's a race currently where some install events may interleave with an uninstall.
2168                // This can lead to package info being null (b/36642664).
2169                if (info != null) {
2170                    mDexManager.notifyPackageInstalled(info, userId);
2171                }
2172            }
2173        }
2174
2175        // If someone is watching installs - notify them
2176        if (installObserver != null) {
2177            try {
2178                Bundle extras = extrasForInstallResult(res);
2179                installObserver.onPackageInstalled(res.name, res.returnCode,
2180                        res.returnMsg, extras);
2181            } catch (RemoteException e) {
2182                Slog.i(TAG, "Observer no longer exists.");
2183            }
2184        }
2185    }
2186
2187    private StorageEventListener mStorageListener = new StorageEventListener() {
2188        @Override
2189        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2190            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2191                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2192                    final String volumeUuid = vol.getFsUuid();
2193
2194                    // Clean up any users or apps that were removed or recreated
2195                    // while this volume was missing
2196                    sUserManager.reconcileUsers(volumeUuid);
2197                    reconcileApps(volumeUuid);
2198
2199                    // Clean up any install sessions that expired or were
2200                    // cancelled while this volume was missing
2201                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2202
2203                    loadPrivatePackages(vol);
2204
2205                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2206                    unloadPrivatePackages(vol);
2207                }
2208            }
2209        }
2210
2211        @Override
2212        public void onVolumeForgotten(String fsUuid) {
2213            if (TextUtils.isEmpty(fsUuid)) {
2214                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2215                return;
2216            }
2217
2218            // Remove any apps installed on the forgotten volume
2219            synchronized (mPackages) {
2220                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2221                for (PackageSetting ps : packages) {
2222                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2223                    deletePackageVersioned(new VersionedPackage(ps.name,
2224                            PackageManager.VERSION_CODE_HIGHEST),
2225                            new LegacyPackageDeleteObserver(null).getBinder(),
2226                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2227                    // Try very hard to release any references to this package
2228                    // so we don't risk the system server being killed due to
2229                    // open FDs
2230                    AttributeCache.instance().removePackage(ps.name);
2231                }
2232
2233                mSettings.onVolumeForgotten(fsUuid);
2234                mSettings.writeLPr();
2235            }
2236        }
2237    };
2238
2239    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2240        Bundle extras = null;
2241        switch (res.returnCode) {
2242            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2243                extras = new Bundle();
2244                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2245                        res.origPermission);
2246                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2247                        res.origPackage);
2248                break;
2249            }
2250            case PackageManager.INSTALL_SUCCEEDED: {
2251                extras = new Bundle();
2252                extras.putBoolean(Intent.EXTRA_REPLACING,
2253                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2254                break;
2255            }
2256        }
2257        return extras;
2258    }
2259
2260    void scheduleWriteSettingsLocked() {
2261        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2262            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2263        }
2264    }
2265
2266    void scheduleWritePackageListLocked(int userId) {
2267        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2268            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2269            msg.arg1 = userId;
2270            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2271        }
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2275        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2276        scheduleWritePackageRestrictionsLocked(userId);
2277    }
2278
2279    void scheduleWritePackageRestrictionsLocked(int userId) {
2280        final int[] userIds = (userId == UserHandle.USER_ALL)
2281                ? sUserManager.getUserIds() : new int[]{userId};
2282        for (int nextUserId : userIds) {
2283            if (!sUserManager.exists(nextUserId)) return;
2284            mDirtyUsers.add(nextUserId);
2285            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2286                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2287            }
2288        }
2289    }
2290
2291    public static PackageManagerService main(Context context, Installer installer,
2292            boolean factoryTest, boolean onlyCore) {
2293        // Self-check for initial settings.
2294        PackageManagerServiceCompilerMapping.checkProperties();
2295
2296        PackageManagerService m = new PackageManagerService(context, installer,
2297                factoryTest, onlyCore);
2298        m.enableSystemUserPackages();
2299        ServiceManager.addService("package", m);
2300        final PackageManagerNative pmn = m.new PackageManagerNative();
2301        ServiceManager.addService("package_native", pmn);
2302        return m;
2303    }
2304
2305    private void enableSystemUserPackages() {
2306        if (!UserManager.isSplitSystemUser()) {
2307            return;
2308        }
2309        // For system user, enable apps based on the following conditions:
2310        // - app is whitelisted or belong to one of these groups:
2311        //   -- system app which has no launcher icons
2312        //   -- system app which has INTERACT_ACROSS_USERS permission
2313        //   -- system IME app
2314        // - app is not in the blacklist
2315        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2316        Set<String> enableApps = new ArraySet<>();
2317        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2318                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2319                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2320        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2321        enableApps.addAll(wlApps);
2322        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2323                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2324        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2325        enableApps.removeAll(blApps);
2326        Log.i(TAG, "Applications installed for system user: " + enableApps);
2327        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2328                UserHandle.SYSTEM);
2329        final int allAppsSize = allAps.size();
2330        synchronized (mPackages) {
2331            for (int i = 0; i < allAppsSize; i++) {
2332                String pName = allAps.get(i);
2333                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2334                // Should not happen, but we shouldn't be failing if it does
2335                if (pkgSetting == null) {
2336                    continue;
2337                }
2338                boolean install = enableApps.contains(pName);
2339                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2340                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2341                            + " for system user");
2342                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2343                }
2344            }
2345            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2346        }
2347    }
2348
2349    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2350        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2351                Context.DISPLAY_SERVICE);
2352        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2353    }
2354
2355    /**
2356     * Requests that files preopted on a secondary system partition be copied to the data partition
2357     * if possible.  Note that the actual copying of the files is accomplished by init for security
2358     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2359     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2360     */
2361    private static void requestCopyPreoptedFiles() {
2362        final int WAIT_TIME_MS = 100;
2363        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2364        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2365            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2366            // We will wait for up to 100 seconds.
2367            final long timeStart = SystemClock.uptimeMillis();
2368            final long timeEnd = timeStart + 100 * 1000;
2369            long timeNow = timeStart;
2370            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2371                try {
2372                    Thread.sleep(WAIT_TIME_MS);
2373                } catch (InterruptedException e) {
2374                    // Do nothing
2375                }
2376                timeNow = SystemClock.uptimeMillis();
2377                if (timeNow > timeEnd) {
2378                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2379                    Slog.wtf(TAG, "cppreopt did not finish!");
2380                    break;
2381                }
2382            }
2383
2384            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2385        }
2386    }
2387
2388    public PackageManagerService(Context context, Installer installer,
2389            boolean factoryTest, boolean onlyCore) {
2390        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2391        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2392        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2393                SystemClock.uptimeMillis());
2394
2395        if (mSdkVersion <= 0) {
2396            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2397        }
2398
2399        mContext = context;
2400
2401        mFactoryTest = factoryTest;
2402        mOnlyCore = onlyCore;
2403        mMetrics = new DisplayMetrics();
2404        mInstaller = installer;
2405
2406        // Create sub-components that provide services / data. Order here is important.
2407        synchronized (mInstallLock) {
2408        synchronized (mPackages) {
2409            // Expose private service for system components to use.
2410            LocalServices.addService(
2411                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2412            sUserManager = new UserManagerService(context, this,
2413                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2414            mPermissionManager = PermissionManagerService.create(context,
2415                    new DefaultPermissionGrantedCallback() {
2416                        @Override
2417                        public void onDefaultRuntimePermissionsGranted(int userId) {
2418                            synchronized(mPackages) {
2419                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2420                            }
2421                        }
2422                    }, mPackages /*externalLock*/);
2423            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2424            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2425        }
2426        }
2427        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2440                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2441
2442        String separateProcesses = SystemProperties.get("debug.separate_processes");
2443        if (separateProcesses != null && separateProcesses.length() > 0) {
2444            if ("*".equals(separateProcesses)) {
2445                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2446                mSeparateProcesses = null;
2447                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2448            } else {
2449                mDefParseFlags = 0;
2450                mSeparateProcesses = separateProcesses.split(",");
2451                Slog.w(TAG, "Running with debug.separate_processes: "
2452                        + separateProcesses);
2453            }
2454        } else {
2455            mDefParseFlags = 0;
2456            mSeparateProcesses = null;
2457        }
2458
2459        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2460                "*dexopt*");
2461        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2462                installer, mInstallLock);
2463        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2464                dexManagerListener);
2465        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2466        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2467
2468        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2469                FgThread.get().getLooper());
2470
2471        getDefaultDisplayMetrics(context, mMetrics);
2472
2473        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2474        SystemConfig systemConfig = SystemConfig.getInstance();
2475        mAvailableFeatures = systemConfig.getAvailableFeatures();
2476        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2477
2478        mProtectedPackages = new ProtectedPackages(mContext);
2479
2480        synchronized (mInstallLock) {
2481        // writer
2482        synchronized (mPackages) {
2483            mHandlerThread = new ServiceThread(TAG,
2484                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2485            mHandlerThread.start();
2486            mHandler = new PackageHandler(mHandlerThread.getLooper());
2487            mProcessLoggingHandler = new ProcessLoggingHandler();
2488            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2489            mInstantAppRegistry = new InstantAppRegistry(this);
2490
2491            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2492            final int builtInLibCount = libConfig.size();
2493            for (int i = 0; i < builtInLibCount; i++) {
2494                String name = libConfig.keyAt(i);
2495                String path = libConfig.valueAt(i);
2496                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2497                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2498            }
2499
2500            SELinuxMMAC.readInstallPolicy();
2501
2502            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2503            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2505
2506            // Clean up orphaned packages for which the code path doesn't exist
2507            // and they are an update to a system app - caused by bug/32321269
2508            final int packageSettingCount = mSettings.mPackages.size();
2509            for (int i = packageSettingCount - 1; i >= 0; i--) {
2510                PackageSetting ps = mSettings.mPackages.valueAt(i);
2511                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2512                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2513                    mSettings.mPackages.removeAt(i);
2514                    mSettings.enableSystemPackageLPw(ps.name);
2515                }
2516            }
2517
2518            if (mFirstBoot) {
2519                requestCopyPreoptedFiles();
2520            }
2521
2522            String customResolverActivity = Resources.getSystem().getString(
2523                    R.string.config_customResolverActivity);
2524            if (TextUtils.isEmpty(customResolverActivity)) {
2525                customResolverActivity = null;
2526            } else {
2527                mCustomResolverComponentName = ComponentName.unflattenFromString(
2528                        customResolverActivity);
2529            }
2530
2531            long startTime = SystemClock.uptimeMillis();
2532
2533            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2534                    startTime);
2535
2536            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2537            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2538
2539            if (bootClassPath == null) {
2540                Slog.w(TAG, "No BOOTCLASSPATH found!");
2541            }
2542
2543            if (systemServerClassPath == null) {
2544                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2545            }
2546
2547            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2548
2549            final VersionInfo ver = mSettings.getInternalVersion();
2550            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2551            if (mIsUpgrade) {
2552                logCriticalInfo(Log.INFO,
2553                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2554            }
2555
2556            // when upgrading from pre-M, promote system app permissions from install to runtime
2557            mPromoteSystemApps =
2558                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2559
2560            // When upgrading from pre-N, we need to handle package extraction like first boot,
2561            // as there is no profiling data available.
2562            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2563
2564            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2565
2566            // save off the names of pre-existing system packages prior to scanning; we don't
2567            // want to automatically grant runtime permissions for new system apps
2568            if (mPromoteSystemApps) {
2569                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2570                while (pkgSettingIter.hasNext()) {
2571                    PackageSetting ps = pkgSettingIter.next();
2572                    if (isSystemApp(ps)) {
2573                        mExistingSystemPackages.add(ps.name);
2574                    }
2575                }
2576            }
2577
2578            mCacheDir = preparePackageParserCache(mIsUpgrade);
2579
2580            // Set flag to monitor and not change apk file paths when
2581            // scanning install directories.
2582            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2583
2584            if (mIsUpgrade || mFirstBoot) {
2585                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2586            }
2587
2588            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2589            // For security and version matching reason, only consider
2590            // overlay packages if they reside in the right directory.
2591            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2592                    mDefParseFlags
2593                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2594                    scanFlags
2595                    | SCAN_AS_SYSTEM
2596                    | SCAN_AS_VENDOR,
2597                    0);
2598            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2599                    mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2601                    scanFlags
2602                    | SCAN_AS_SYSTEM
2603                    | SCAN_AS_PRODUCT,
2604                    0);
2605
2606            mParallelPackageParserCallback.findStaticOverlayPackages();
2607
2608            // Find base frameworks (resource packages without code).
2609            scanDirTracedLI(frameworkDir,
2610                    mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2612                    scanFlags
2613                    | SCAN_NO_DEX
2614                    | SCAN_AS_SYSTEM
2615                    | SCAN_AS_PRIVILEGED,
2616                    0);
2617
2618            // Collect privileged system packages.
2619            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2620            scanDirTracedLI(privilegedAppDir,
2621                    mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2623                    scanFlags
2624                    | SCAN_AS_SYSTEM
2625                    | SCAN_AS_PRIVILEGED,
2626                    0);
2627
2628            // Collect ordinary system packages.
2629            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2630            scanDirTracedLI(systemAppDir,
2631                    mDefParseFlags
2632                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2633                    scanFlags
2634                    | SCAN_AS_SYSTEM,
2635                    0);
2636
2637            // Collect privileged vendor packages.
2638            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2639            try {
2640                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2641            } catch (IOException e) {
2642                // failed to look up canonical path, continue with original one
2643            }
2644            scanDirTracedLI(privilegedVendorAppDir,
2645                    mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2647                    scanFlags
2648                    | SCAN_AS_SYSTEM
2649                    | SCAN_AS_VENDOR
2650                    | SCAN_AS_PRIVILEGED,
2651                    0);
2652
2653            // Collect ordinary vendor packages.
2654            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2655            try {
2656                vendorAppDir = vendorAppDir.getCanonicalFile();
2657            } catch (IOException e) {
2658                // failed to look up canonical path, continue with original one
2659            }
2660            scanDirTracedLI(vendorAppDir,
2661                    mDefParseFlags
2662                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2663                    scanFlags
2664                    | SCAN_AS_SYSTEM
2665                    | SCAN_AS_VENDOR,
2666                    0);
2667
2668            // Collect privileged odm packages. /odm is another vendor partition
2669            // other than /vendor.
2670            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2671                        "priv-app");
2672            try {
2673                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2674            } catch (IOException e) {
2675                // failed to look up canonical path, continue with original one
2676            }
2677            scanDirTracedLI(privilegedOdmAppDir,
2678                    mDefParseFlags
2679                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2680                    scanFlags
2681                    | SCAN_AS_SYSTEM
2682                    | SCAN_AS_VENDOR
2683                    | SCAN_AS_PRIVILEGED,
2684                    0);
2685
2686            // Collect ordinary odm packages. /odm is another vendor partition
2687            // other than /vendor.
2688            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2689            try {
2690                odmAppDir = odmAppDir.getCanonicalFile();
2691            } catch (IOException e) {
2692                // failed to look up canonical path, continue with original one
2693            }
2694            scanDirTracedLI(odmAppDir,
2695                    mDefParseFlags
2696                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2697                    scanFlags
2698                    | SCAN_AS_SYSTEM
2699                    | SCAN_AS_VENDOR,
2700                    0);
2701
2702            // Collect all OEM packages.
2703            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2704            scanDirTracedLI(oemAppDir,
2705                    mDefParseFlags
2706                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2707                    scanFlags
2708                    | SCAN_AS_SYSTEM
2709                    | SCAN_AS_OEM,
2710                    0);
2711
2712            // Collected privileged product packages.
2713            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2714            try {
2715                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2716            } catch (IOException e) {
2717                // failed to look up canonical path, continue with original one
2718            }
2719            scanDirTracedLI(privilegedProductAppDir,
2720                    mDefParseFlags
2721                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2722                    scanFlags
2723                    | SCAN_AS_SYSTEM
2724                    | SCAN_AS_PRODUCT
2725                    | SCAN_AS_PRIVILEGED,
2726                    0);
2727
2728            // Collect ordinary product packages.
2729            File productAppDir = new File(Environment.getProductDirectory(), "app");
2730            try {
2731                productAppDir = productAppDir.getCanonicalFile();
2732            } catch (IOException e) {
2733                // failed to look up canonical path, continue with original one
2734            }
2735            scanDirTracedLI(productAppDir,
2736                    mDefParseFlags
2737                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2738                    scanFlags
2739                    | SCAN_AS_SYSTEM
2740                    | SCAN_AS_PRODUCT,
2741                    0);
2742
2743            // Prune any system packages that no longer exist.
2744            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2745            // Stub packages must either be replaced with full versions in the /data
2746            // partition or be disabled.
2747            final List<String> stubSystemApps = new ArrayList<>();
2748            if (!mOnlyCore) {
2749                // do this first before mucking with mPackages for the "expecting better" case
2750                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2751                while (pkgIterator.hasNext()) {
2752                    final PackageParser.Package pkg = pkgIterator.next();
2753                    if (pkg.isStub) {
2754                        stubSystemApps.add(pkg.packageName);
2755                    }
2756                }
2757
2758                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2759                while (psit.hasNext()) {
2760                    PackageSetting ps = psit.next();
2761
2762                    /*
2763                     * If this is not a system app, it can't be a
2764                     * disable system app.
2765                     */
2766                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2767                        continue;
2768                    }
2769
2770                    /*
2771                     * If the package is scanned, it's not erased.
2772                     */
2773                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2774                    if (scannedPkg != null) {
2775                        /*
2776                         * If the system app is both scanned and in the
2777                         * disabled packages list, then it must have been
2778                         * added via OTA. Remove it from the currently
2779                         * scanned package so the previously user-installed
2780                         * application can be scanned.
2781                         */
2782                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2783                            logCriticalInfo(Log.WARN,
2784                                    "Expecting better updated system app for " + ps.name
2785                                    + "; removing system app.  Last known"
2786                                    + " codePath=" + ps.codePathString
2787                                    + ", versionCode=" + ps.versionCode
2788                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2789                            removePackageLI(scannedPkg, true);
2790                            mExpectingBetter.put(ps.name, ps.codePath);
2791                        }
2792
2793                        continue;
2794                    }
2795
2796                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2797                        psit.remove();
2798                        logCriticalInfo(Log.WARN, "System package " + ps.name
2799                                + " no longer exists; it's data will be wiped");
2800                        // Actual deletion of code and data will be handled by later
2801                        // reconciliation step
2802                    } else {
2803                        // we still have a disabled system package, but, it still might have
2804                        // been removed. check the code path still exists and check there's
2805                        // still a package. the latter can happen if an OTA keeps the same
2806                        // code path, but, changes the package name.
2807                        final PackageSetting disabledPs =
2808                                mSettings.getDisabledSystemPkgLPr(ps.name);
2809                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2810                                || disabledPs.pkg == null) {
2811                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2812                        }
2813                    }
2814                }
2815            }
2816
2817            //delete tmp files
2818            deleteTempPackageFiles();
2819
2820            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2821
2822            // Remove any shared userIDs that have no associated packages
2823            mSettings.pruneSharedUsersLPw();
2824            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2825            final int systemPackagesCount = mPackages.size();
2826            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2827                    + " ms, packageCount: " + systemPackagesCount
2828                    + " , timePerPackage: "
2829                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2830                    + " , cached: " + cachedSystemApps);
2831            if (mIsUpgrade && systemPackagesCount > 0) {
2832                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2833                        ((int) systemScanTime) / systemPackagesCount);
2834            }
2835            if (!mOnlyCore) {
2836                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2837                        SystemClock.uptimeMillis());
2838                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2839
2840                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2841                        | PackageParser.PARSE_FORWARD_LOCK,
2842                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2843
2844                // Remove disable package settings for updated system apps that were
2845                // removed via an OTA. If the update is no longer present, remove the
2846                // app completely. Otherwise, revoke their system privileges.
2847                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2848                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2849                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2850                    final String msg;
2851                    if (deletedPkg == null) {
2852                        // should have found an update, but, we didn't; remove everything
2853                        msg = "Updated system package " + deletedAppName
2854                                + " no longer exists; removing its data";
2855                        // Actual deletion of code and data will be handled by later
2856                        // reconciliation step
2857                    } else {
2858                        // found an update; revoke system privileges
2859                        msg = "Updated system package + " + deletedAppName
2860                                + " no longer exists; revoking system privileges";
2861
2862                        // Don't do anything if a stub is removed from the system image. If
2863                        // we were to remove the uncompressed version from the /data partition,
2864                        // this is where it'd be done.
2865
2866                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2867                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2868                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2869                    }
2870                    logCriticalInfo(Log.WARN, msg);
2871                }
2872
2873                /*
2874                 * Make sure all system apps that we expected to appear on
2875                 * the userdata partition actually showed up. If they never
2876                 * appeared, crawl back and revive the system version.
2877                 */
2878                for (int i = 0; i < mExpectingBetter.size(); i++) {
2879                    final String packageName = mExpectingBetter.keyAt(i);
2880                    if (!mPackages.containsKey(packageName)) {
2881                        final File scanFile = mExpectingBetter.valueAt(i);
2882
2883                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2884                                + " but never showed up; reverting to system");
2885
2886                        final @ParseFlags int reparseFlags;
2887                        final @ScanFlags int rescanFlags;
2888                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2889                            reparseFlags =
2890                                    mDefParseFlags |
2891                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2892                            rescanFlags =
2893                                    scanFlags
2894                                    | SCAN_AS_SYSTEM
2895                                    | SCAN_AS_PRIVILEGED;
2896                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2897                            reparseFlags =
2898                                    mDefParseFlags |
2899                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2900                            rescanFlags =
2901                                    scanFlags
2902                                    | SCAN_AS_SYSTEM;
2903                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2904                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2905                            reparseFlags =
2906                                    mDefParseFlags |
2907                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2908                            rescanFlags =
2909                                    scanFlags
2910                                    | SCAN_AS_SYSTEM
2911                                    | SCAN_AS_VENDOR
2912                                    | SCAN_AS_PRIVILEGED;
2913                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2914                                || FileUtils.contains(odmAppDir, scanFile)) {
2915                            reparseFlags =
2916                                    mDefParseFlags |
2917                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2918                            rescanFlags =
2919                                    scanFlags
2920                                    | SCAN_AS_SYSTEM
2921                                    | SCAN_AS_VENDOR;
2922                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2923                            reparseFlags =
2924                                    mDefParseFlags |
2925                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2926                            rescanFlags =
2927                                    scanFlags
2928                                    | SCAN_AS_SYSTEM
2929                                    | SCAN_AS_OEM;
2930                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2931                            reparseFlags =
2932                                    mDefParseFlags |
2933                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2934                            rescanFlags =
2935                                    scanFlags
2936                                    | SCAN_AS_SYSTEM
2937                                    | SCAN_AS_PRODUCT
2938                                    | SCAN_AS_PRIVILEGED;
2939                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2940                            reparseFlags =
2941                                    mDefParseFlags |
2942                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2943                            rescanFlags =
2944                                    scanFlags
2945                                    | SCAN_AS_SYSTEM
2946                                    | SCAN_AS_PRODUCT;
2947                        } else {
2948                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2949                            continue;
2950                        }
2951
2952                        mSettings.enableSystemPackageLPw(packageName);
2953
2954                        try {
2955                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2956                        } catch (PackageManagerException e) {
2957                            Slog.e(TAG, "Failed to parse original system package: "
2958                                    + e.getMessage());
2959                        }
2960                    }
2961                }
2962
2963                // Uncompress and install any stubbed system applications.
2964                // This must be done last to ensure all stubs are replaced or disabled.
2965                decompressSystemApplications(stubSystemApps, scanFlags);
2966
2967                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2968                                - cachedSystemApps;
2969
2970                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2971                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2972                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2973                        + " ms, packageCount: " + dataPackagesCount
2974                        + " , timePerPackage: "
2975                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2976                        + " , cached: " + cachedNonSystemApps);
2977                if (mIsUpgrade && dataPackagesCount > 0) {
2978                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2979                            ((int) dataScanTime) / dataPackagesCount);
2980                }
2981            }
2982            mExpectingBetter.clear();
2983
2984            // Resolve the storage manager.
2985            mStorageManagerPackage = getStorageManagerPackageName();
2986
2987            // Resolve protected action filters. Only the setup wizard is allowed to
2988            // have a high priority filter for these actions.
2989            mSetupWizardPackage = getSetupWizardPackageName();
2990            if (mProtectedFilters.size() > 0) {
2991                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2992                    Slog.i(TAG, "No setup wizard;"
2993                        + " All protected intents capped to priority 0");
2994                }
2995                for (ActivityIntentInfo filter : mProtectedFilters) {
2996                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2997                        if (DEBUG_FILTERS) {
2998                            Slog.i(TAG, "Found setup wizard;"
2999                                + " allow priority " + filter.getPriority() + ";"
3000                                + " package: " + filter.activity.info.packageName
3001                                + " activity: " + filter.activity.className
3002                                + " priority: " + filter.getPriority());
3003                        }
3004                        // skip setup wizard; allow it to keep the high priority filter
3005                        continue;
3006                    }
3007                    if (DEBUG_FILTERS) {
3008                        Slog.i(TAG, "Protected action; cap priority to 0;"
3009                                + " package: " + filter.activity.info.packageName
3010                                + " activity: " + filter.activity.className
3011                                + " origPrio: " + filter.getPriority());
3012                    }
3013                    filter.setPriority(0);
3014                }
3015            }
3016
3017            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3018
3019            mDeferProtectedFilters = false;
3020            mProtectedFilters.clear();
3021
3022            // Now that we know all of the shared libraries, update all clients to have
3023            // the correct library paths.
3024            updateAllSharedLibrariesLPw(null);
3025
3026            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3027                // NOTE: We ignore potential failures here during a system scan (like
3028                // the rest of the commands above) because there's precious little we
3029                // can do about it. A settings error is reported, though.
3030                final List<String> changedAbiCodePath =
3031                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3032                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3033                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3034                        final String codePathString = changedAbiCodePath.get(i);
3035                        try {
3036                            mInstaller.rmdex(codePathString,
3037                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3038                        } catch (InstallerException ignored) {
3039                        }
3040                    }
3041                }
3042                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3043                // SELinux domain.
3044                setting.fixSeInfoLocked();
3045            }
3046
3047            // Now that we know all the packages we are keeping,
3048            // read and update their last usage times.
3049            mPackageUsage.read(mPackages);
3050            mCompilerStats.read();
3051
3052            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3053                    SystemClock.uptimeMillis());
3054            Slog.i(TAG, "Time to scan packages: "
3055                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3056                    + " seconds");
3057
3058            // If the platform SDK has changed since the last time we booted,
3059            // we need to re-grant app permission to catch any new ones that
3060            // appear.  This is really a hack, and means that apps can in some
3061            // cases get permissions that the user didn't initially explicitly
3062            // allow...  it would be nice to have some better way to handle
3063            // this situation.
3064            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3065            if (sdkUpdated) {
3066                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3067                        + mSdkVersion + "; regranting permissions for internal storage");
3068            }
3069            mPermissionManager.updateAllPermissions(
3070                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3071                    mPermissionCallback);
3072            ver.sdkVersion = mSdkVersion;
3073
3074            // If this is the first boot or an update from pre-M, and it is a normal
3075            // boot, then we need to initialize the default preferred apps across
3076            // all defined users.
3077            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3078                for (UserInfo user : sUserManager.getUsers(true)) {
3079                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3080                    applyFactoryDefaultBrowserLPw(user.id);
3081                    primeDomainVerificationsLPw(user.id);
3082                }
3083            }
3084
3085            // Prepare storage for system user really early during boot,
3086            // since core system apps like SettingsProvider and SystemUI
3087            // can't wait for user to start
3088            final int storageFlags;
3089            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3090                storageFlags = StorageManager.FLAG_STORAGE_DE;
3091            } else {
3092                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3093            }
3094            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3095                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3096                    true /* onlyCoreApps */);
3097            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3098                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3099                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3100                traceLog.traceBegin("AppDataFixup");
3101                try {
3102                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3103                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3104                } catch (InstallerException e) {
3105                    Slog.w(TAG, "Trouble fixing GIDs", e);
3106                }
3107                traceLog.traceEnd();
3108
3109                traceLog.traceBegin("AppDataPrepare");
3110                if (deferPackages == null || deferPackages.isEmpty()) {
3111                    return;
3112                }
3113                int count = 0;
3114                for (String pkgName : deferPackages) {
3115                    PackageParser.Package pkg = null;
3116                    synchronized (mPackages) {
3117                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3118                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3119                            pkg = ps.pkg;
3120                        }
3121                    }
3122                    if (pkg != null) {
3123                        synchronized (mInstallLock) {
3124                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3125                                    true /* maybeMigrateAppData */);
3126                        }
3127                        count++;
3128                    }
3129                }
3130                traceLog.traceEnd();
3131                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3132            }, "prepareAppData");
3133
3134            // If this is first boot after an OTA, and a normal boot, then
3135            // we need to clear code cache directories.
3136            // Note that we do *not* clear the application profiles. These remain valid
3137            // across OTAs and are used to drive profile verification (post OTA) and
3138            // profile compilation (without waiting to collect a fresh set of profiles).
3139            if (mIsUpgrade && !onlyCore) {
3140                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3141                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3142                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3143                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3144                        // No apps are running this early, so no need to freeze
3145                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3146                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3147                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3148                    }
3149                }
3150                ver.fingerprint = Build.FINGERPRINT;
3151            }
3152
3153            checkDefaultBrowser();
3154
3155            // clear only after permissions and other defaults have been updated
3156            mExistingSystemPackages.clear();
3157            mPromoteSystemApps = false;
3158
3159            // All the changes are done during package scanning.
3160            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3161
3162            // can downgrade to reader
3163            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3164            mSettings.writeLPr();
3165            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3166            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3167                    SystemClock.uptimeMillis());
3168
3169            if (!mOnlyCore) {
3170                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3171                mRequiredInstallerPackage = getRequiredInstallerLPr();
3172                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3173                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3174                if (mIntentFilterVerifierComponent != null) {
3175                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3176                            mIntentFilterVerifierComponent);
3177                } else {
3178                    mIntentFilterVerifier = null;
3179                }
3180                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3181                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3182                        SharedLibraryInfo.VERSION_UNDEFINED);
3183                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3184                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3185                        SharedLibraryInfo.VERSION_UNDEFINED);
3186            } else {
3187                mRequiredVerifierPackage = null;
3188                mRequiredInstallerPackage = null;
3189                mRequiredUninstallerPackage = null;
3190                mIntentFilterVerifierComponent = null;
3191                mIntentFilterVerifier = null;
3192                mServicesSystemSharedLibraryPackageName = null;
3193                mSharedSystemSharedLibraryPackageName = null;
3194            }
3195
3196            mInstallerService = new PackageInstallerService(context, this);
3197            final Pair<ComponentName, String> instantAppResolverComponent =
3198                    getInstantAppResolverLPr();
3199            if (instantAppResolverComponent != null) {
3200                if (DEBUG_INSTANT) {
3201                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3202                }
3203                mInstantAppResolverConnection = new InstantAppResolverConnection(
3204                        mContext, instantAppResolverComponent.first,
3205                        instantAppResolverComponent.second);
3206                mInstantAppResolverSettingsComponent =
3207                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3208            } else {
3209                mInstantAppResolverConnection = null;
3210                mInstantAppResolverSettingsComponent = null;
3211            }
3212            updateInstantAppInstallerLocked(null);
3213
3214            // Read and update the usage of dex files.
3215            // Do this at the end of PM init so that all the packages have their
3216            // data directory reconciled.
3217            // At this point we know the code paths of the packages, so we can validate
3218            // the disk file and build the internal cache.
3219            // The usage file is expected to be small so loading and verifying it
3220            // should take a fairly small time compare to the other activities (e.g. package
3221            // scanning).
3222            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3223            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3224            for (int userId : currentUserIds) {
3225                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3226            }
3227            mDexManager.load(userPackages);
3228            if (mIsUpgrade) {
3229                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3230                        (int) (SystemClock.uptimeMillis() - startTime));
3231            }
3232        } // synchronized (mPackages)
3233        } // synchronized (mInstallLock)
3234
3235        // Now after opening every single application zip, make sure they
3236        // are all flushed.  Not really needed, but keeps things nice and
3237        // tidy.
3238        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3239        Runtime.getRuntime().gc();
3240        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3241
3242        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3243        FallbackCategoryProvider.loadFallbacks();
3244        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3245
3246        // The initial scanning above does many calls into installd while
3247        // holding the mPackages lock, but we're mostly interested in yelling
3248        // once we have a booted system.
3249        mInstaller.setWarnIfHeld(mPackages);
3250
3251        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3252    }
3253
3254    /**
3255     * Uncompress and install stub applications.
3256     * <p>In order to save space on the system partition, some applications are shipped in a
3257     * compressed form. In addition the compressed bits for the full application, the
3258     * system image contains a tiny stub comprised of only the Android manifest.
3259     * <p>During the first boot, attempt to uncompress and install the full application. If
3260     * the application can't be installed for any reason, disable the stub and prevent
3261     * uncompressing the full application during future boots.
3262     * <p>In order to forcefully attempt an installation of a full application, go to app
3263     * settings and enable the application.
3264     */
3265    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3266        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3267            final String pkgName = stubSystemApps.get(i);
3268            // skip if the system package is already disabled
3269            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3270                stubSystemApps.remove(i);
3271                continue;
3272            }
3273            // skip if the package isn't installed (?!); this should never happen
3274            final PackageParser.Package pkg = mPackages.get(pkgName);
3275            if (pkg == null) {
3276                stubSystemApps.remove(i);
3277                continue;
3278            }
3279            // skip if the package has been disabled by the user
3280            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3281            if (ps != null) {
3282                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3283                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3284                    stubSystemApps.remove(i);
3285                    continue;
3286                }
3287            }
3288
3289            if (DEBUG_COMPRESSION) {
3290                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3291            }
3292
3293            // uncompress the binary to its eventual destination on /data
3294            final File scanFile = decompressPackage(pkg);
3295            if (scanFile == null) {
3296                continue;
3297            }
3298
3299            // install the package to replace the stub on /system
3300            try {
3301                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3302                removePackageLI(pkg, true /*chatty*/);
3303                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3304                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3305                        UserHandle.USER_SYSTEM, "android");
3306                stubSystemApps.remove(i);
3307                continue;
3308            } catch (PackageManagerException e) {
3309                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3310            }
3311
3312            // any failed attempt to install the package will be cleaned up later
3313        }
3314
3315        // disable any stub still left; these failed to install the full application
3316        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3317            final String pkgName = stubSystemApps.get(i);
3318            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3319            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3320                    UserHandle.USER_SYSTEM, "android");
3321            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3322        }
3323    }
3324
3325    /**
3326     * Decompresses the given package on the system image onto
3327     * the /data partition.
3328     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3329     */
3330    private File decompressPackage(PackageParser.Package pkg) {
3331        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3332        if (compressedFiles == null || compressedFiles.length == 0) {
3333            if (DEBUG_COMPRESSION) {
3334                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3335            }
3336            return null;
3337        }
3338        final File dstCodePath =
3339                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3340        int ret = PackageManager.INSTALL_SUCCEEDED;
3341        try {
3342            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3343            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3344            for (File srcFile : compressedFiles) {
3345                final String srcFileName = srcFile.getName();
3346                final String dstFileName = srcFileName.substring(
3347                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3348                final File dstFile = new File(dstCodePath, dstFileName);
3349                ret = decompressFile(srcFile, dstFile);
3350                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3351                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3352                            + "; pkg: " + pkg.packageName
3353                            + ", file: " + dstFileName);
3354                    break;
3355                }
3356            }
3357        } catch (ErrnoException e) {
3358            logCriticalInfo(Log.ERROR, "Failed to decompress"
3359                    + "; pkg: " + pkg.packageName
3360                    + ", err: " + e.errno);
3361        }
3362        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3363            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3364            NativeLibraryHelper.Handle handle = null;
3365            try {
3366                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3367                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3368                        null /*abiOverride*/);
3369            } catch (IOException e) {
3370                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3371                        + "; pkg: " + pkg.packageName);
3372                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3373            } finally {
3374                IoUtils.closeQuietly(handle);
3375            }
3376        }
3377        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3378            if (dstCodePath == null || !dstCodePath.exists()) {
3379                return null;
3380            }
3381            removeCodePathLI(dstCodePath);
3382            return null;
3383        }
3384
3385        return dstCodePath;
3386    }
3387
3388    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3389        // we're only interested in updating the installer appliction when 1) it's not
3390        // already set or 2) the modified package is the installer
3391        if (mInstantAppInstallerActivity != null
3392                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3393                        .equals(modifiedPackage)) {
3394            return;
3395        }
3396        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3397    }
3398
3399    private static File preparePackageParserCache(boolean isUpgrade) {
3400        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3401            return null;
3402        }
3403
3404        // Disable package parsing on eng builds to allow for faster incremental development.
3405        if (Build.IS_ENG) {
3406            return null;
3407        }
3408
3409        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3410            Slog.i(TAG, "Disabling package parser cache due to system property.");
3411            return null;
3412        }
3413
3414        // The base directory for the package parser cache lives under /data/system/.
3415        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3416                "package_cache");
3417        if (cacheBaseDir == null) {
3418            return null;
3419        }
3420
3421        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3422        // This also serves to "GC" unused entries when the package cache version changes (which
3423        // can only happen during upgrades).
3424        if (isUpgrade) {
3425            FileUtils.deleteContents(cacheBaseDir);
3426        }
3427
3428
3429        // Return the versioned package cache directory. This is something like
3430        // "/data/system/package_cache/1"
3431        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3432
3433        if (cacheDir == null) {
3434            // Something went wrong. Attempt to delete everything and return.
3435            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3436            FileUtils.deleteContentsAndDir(cacheBaseDir);
3437            return null;
3438        }
3439
3440        // The following is a workaround to aid development on non-numbered userdebug
3441        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3442        // the system partition is newer.
3443        //
3444        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3445        // that starts with "eng." to signify that this is an engineering build and not
3446        // destined for release.
3447        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3448            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3449
3450            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3451            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3452            // in general and should not be used for production changes. In this specific case,
3453            // we know that they will work.
3454            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3455            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3456                FileUtils.deleteContents(cacheBaseDir);
3457                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3458            }
3459        }
3460
3461        return cacheDir;
3462    }
3463
3464    @Override
3465    public boolean isFirstBoot() {
3466        // allow instant applications
3467        return mFirstBoot;
3468    }
3469
3470    @Override
3471    public boolean isOnlyCoreApps() {
3472        // allow instant applications
3473        return mOnlyCore;
3474    }
3475
3476    @Override
3477    public boolean isUpgrade() {
3478        // allow instant applications
3479        // The system property allows testing ota flow when upgraded to the same image.
3480        return mIsUpgrade || SystemProperties.getBoolean(
3481                "persist.pm.mock-upgrade", false /* default */);
3482    }
3483
3484    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3485        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3486
3487        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3488                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3489                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3490        if (matches.size() == 1) {
3491            return matches.get(0).getComponentInfo().packageName;
3492        } else if (matches.size() == 0) {
3493            Log.e(TAG, "There should probably be a verifier, but, none were found");
3494            return null;
3495        }
3496        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3497    }
3498
3499    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3500        synchronized (mPackages) {
3501            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3502            if (libraryEntry == null) {
3503                throw new IllegalStateException("Missing required shared library:" + name);
3504            }
3505            return libraryEntry.apk;
3506        }
3507    }
3508
3509    private @NonNull String getRequiredInstallerLPr() {
3510        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3511        intent.addCategory(Intent.CATEGORY_DEFAULT);
3512        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3513
3514        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3515                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3516                UserHandle.USER_SYSTEM);
3517        if (matches.size() == 1) {
3518            ResolveInfo resolveInfo = matches.get(0);
3519            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3520                throw new RuntimeException("The installer must be a privileged app");
3521            }
3522            return matches.get(0).getComponentInfo().packageName;
3523        } else {
3524            throw new RuntimeException("There must be exactly one installer; found " + matches);
3525        }
3526    }
3527
3528    private @NonNull String getRequiredUninstallerLPr() {
3529        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3530        intent.addCategory(Intent.CATEGORY_DEFAULT);
3531        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3532
3533        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3534                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3535                UserHandle.USER_SYSTEM);
3536        if (resolveInfo == null ||
3537                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3538            throw new RuntimeException("There must be exactly one uninstaller; found "
3539                    + resolveInfo);
3540        }
3541        return resolveInfo.getComponentInfo().packageName;
3542    }
3543
3544    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3545        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3546
3547        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3548                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3549                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3550        ResolveInfo best = null;
3551        final int N = matches.size();
3552        for (int i = 0; i < N; i++) {
3553            final ResolveInfo cur = matches.get(i);
3554            final String packageName = cur.getComponentInfo().packageName;
3555            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3556                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3557                continue;
3558            }
3559
3560            if (best == null || cur.priority > best.priority) {
3561                best = cur;
3562            }
3563        }
3564
3565        if (best != null) {
3566            return best.getComponentInfo().getComponentName();
3567        }
3568        Slog.w(TAG, "Intent filter verifier not found");
3569        return null;
3570    }
3571
3572    @Override
3573    public @Nullable ComponentName getInstantAppResolverComponent() {
3574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3575            return null;
3576        }
3577        synchronized (mPackages) {
3578            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3579            if (instantAppResolver == null) {
3580                return null;
3581            }
3582            return instantAppResolver.first;
3583        }
3584    }
3585
3586    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3587        final String[] packageArray =
3588                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3589        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3590            if (DEBUG_INSTANT) {
3591                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3592            }
3593            return null;
3594        }
3595
3596        final int callingUid = Binder.getCallingUid();
3597        final int resolveFlags =
3598                MATCH_DIRECT_BOOT_AWARE
3599                | MATCH_DIRECT_BOOT_UNAWARE
3600                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3601        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3602        final Intent resolverIntent = new Intent(actionName);
3603        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3604                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3605        final int N = resolvers.size();
3606        if (N == 0) {
3607            if (DEBUG_INSTANT) {
3608                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3609            }
3610            return null;
3611        }
3612
3613        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3614        for (int i = 0; i < N; i++) {
3615            final ResolveInfo info = resolvers.get(i);
3616
3617            if (info.serviceInfo == null) {
3618                continue;
3619            }
3620
3621            final String packageName = info.serviceInfo.packageName;
3622            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3623                if (DEBUG_INSTANT) {
3624                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3625                            + " pkg: " + packageName + ", info:" + info);
3626                }
3627                continue;
3628            }
3629
3630            if (DEBUG_INSTANT) {
3631                Slog.v(TAG, "Ephemeral resolver found;"
3632                        + " pkg: " + packageName + ", info:" + info);
3633            }
3634            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3635        }
3636        if (DEBUG_INSTANT) {
3637            Slog.v(TAG, "Ephemeral resolver NOT found");
3638        }
3639        return null;
3640    }
3641
3642    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3643        String[] orderedActions = Build.IS_ENG
3644                ? new String[]{
3645                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3646                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3647                : new String[]{
3648                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3649
3650        final int resolveFlags =
3651                MATCH_DIRECT_BOOT_AWARE
3652                        | MATCH_DIRECT_BOOT_UNAWARE
3653                        | Intent.FLAG_IGNORE_EPHEMERAL
3654                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3655        final Intent intent = new Intent();
3656        intent.addCategory(Intent.CATEGORY_DEFAULT);
3657        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3658        List<ResolveInfo> matches = null;
3659        for (String action : orderedActions) {
3660            intent.setAction(action);
3661            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3662                    resolveFlags, UserHandle.USER_SYSTEM);
3663            if (matches.isEmpty()) {
3664                if (DEBUG_INSTANT) {
3665                    Slog.d(TAG, "Instant App installer not found with " + action);
3666                }
3667            } else {
3668                break;
3669            }
3670        }
3671        Iterator<ResolveInfo> iter = matches.iterator();
3672        while (iter.hasNext()) {
3673            final ResolveInfo rInfo = iter.next();
3674            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3675            if (ps != null) {
3676                final PermissionsState permissionsState = ps.getPermissionsState();
3677                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3678                        || Build.IS_ENG) {
3679                    continue;
3680                }
3681            }
3682            iter.remove();
3683        }
3684        if (matches.size() == 0) {
3685            return null;
3686        } else if (matches.size() == 1) {
3687            return (ActivityInfo) matches.get(0).getComponentInfo();
3688        } else {
3689            throw new RuntimeException(
3690                    "There must be at most one ephemeral installer; found " + matches);
3691        }
3692    }
3693
3694    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3695            @NonNull ComponentName resolver) {
3696        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3697                .addCategory(Intent.CATEGORY_DEFAULT)
3698                .setPackage(resolver.getPackageName());
3699        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3700        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3701                UserHandle.USER_SYSTEM);
3702        if (matches.isEmpty()) {
3703            return null;
3704        }
3705        return matches.get(0).getComponentInfo().getComponentName();
3706    }
3707
3708    private void primeDomainVerificationsLPw(int userId) {
3709        if (DEBUG_DOMAIN_VERIFICATION) {
3710            Slog.d(TAG, "Priming domain verifications in user " + userId);
3711        }
3712
3713        SystemConfig systemConfig = SystemConfig.getInstance();
3714        ArraySet<String> packages = systemConfig.getLinkedApps();
3715
3716        for (String packageName : packages) {
3717            PackageParser.Package pkg = mPackages.get(packageName);
3718            if (pkg != null) {
3719                if (!pkg.isSystem()) {
3720                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3721                    continue;
3722                }
3723
3724                ArraySet<String> domains = null;
3725                for (PackageParser.Activity a : pkg.activities) {
3726                    for (ActivityIntentInfo filter : a.intents) {
3727                        if (hasValidDomains(filter)) {
3728                            if (domains == null) {
3729                                domains = new ArraySet<String>();
3730                            }
3731                            domains.addAll(filter.getHostsList());
3732                        }
3733                    }
3734                }
3735
3736                if (domains != null && domains.size() > 0) {
3737                    if (DEBUG_DOMAIN_VERIFICATION) {
3738                        Slog.v(TAG, "      + " + packageName);
3739                    }
3740                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3741                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3742                    // and then 'always' in the per-user state actually used for intent resolution.
3743                    final IntentFilterVerificationInfo ivi;
3744                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3745                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3746                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3747                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3748                } else {
3749                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3750                            + "' does not handle web links");
3751                }
3752            } else {
3753                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3754            }
3755        }
3756
3757        scheduleWritePackageRestrictionsLocked(userId);
3758        scheduleWriteSettingsLocked();
3759    }
3760
3761    private void applyFactoryDefaultBrowserLPw(int userId) {
3762        // The default browser app's package name is stored in a string resource,
3763        // with a product-specific overlay used for vendor customization.
3764        String browserPkg = mContext.getResources().getString(
3765                com.android.internal.R.string.default_browser);
3766        if (!TextUtils.isEmpty(browserPkg)) {
3767            // non-empty string => required to be a known package
3768            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3769            if (ps == null) {
3770                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3771                browserPkg = null;
3772            } else {
3773                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3774            }
3775        }
3776
3777        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3778        // default.  If there's more than one, just leave everything alone.
3779        if (browserPkg == null) {
3780            calculateDefaultBrowserLPw(userId);
3781        }
3782    }
3783
3784    private void calculateDefaultBrowserLPw(int userId) {
3785        List<String> allBrowsers = resolveAllBrowserApps(userId);
3786        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3787        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3788    }
3789
3790    private List<String> resolveAllBrowserApps(int userId) {
3791        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3792        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3793                PackageManager.MATCH_ALL, userId);
3794
3795        final int count = list.size();
3796        List<String> result = new ArrayList<String>(count);
3797        for (int i=0; i<count; i++) {
3798            ResolveInfo info = list.get(i);
3799            if (info.activityInfo == null
3800                    || !info.handleAllWebDataURI
3801                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3802                    || result.contains(info.activityInfo.packageName)) {
3803                continue;
3804            }
3805            result.add(info.activityInfo.packageName);
3806        }
3807
3808        return result;
3809    }
3810
3811    private boolean packageIsBrowser(String packageName, int userId) {
3812        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3813                PackageManager.MATCH_ALL, userId);
3814        final int N = list.size();
3815        for (int i = 0; i < N; i++) {
3816            ResolveInfo info = list.get(i);
3817            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3818                return true;
3819            }
3820        }
3821        return false;
3822    }
3823
3824    private void checkDefaultBrowser() {
3825        final int myUserId = UserHandle.myUserId();
3826        final String packageName = getDefaultBrowserPackageName(myUserId);
3827        if (packageName != null) {
3828            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3829            if (info == null) {
3830                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3831                synchronized (mPackages) {
3832                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3833                }
3834            }
3835        }
3836    }
3837
3838    @Override
3839    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3840            throws RemoteException {
3841        try {
3842            return super.onTransact(code, data, reply, flags);
3843        } catch (RuntimeException e) {
3844            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3845                Slog.wtf(TAG, "Package Manager Crash", e);
3846            }
3847            throw e;
3848        }
3849    }
3850
3851    static int[] appendInts(int[] cur, int[] add) {
3852        if (add == null) return cur;
3853        if (cur == null) return add;
3854        final int N = add.length;
3855        for (int i=0; i<N; i++) {
3856            cur = appendInt(cur, add[i]);
3857        }
3858        return cur;
3859    }
3860
3861    /**
3862     * Returns whether or not a full application can see an instant application.
3863     * <p>
3864     * Currently, there are three cases in which this can occur:
3865     * <ol>
3866     * <li>The calling application is a "special" process. Special processes
3867     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3868     * <li>The calling application has the permission
3869     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3870     * <li>The calling application is the default launcher on the
3871     *     system partition.</li>
3872     * </ol>
3873     */
3874    private boolean canViewInstantApps(int callingUid, int userId) {
3875        if (callingUid < Process.FIRST_APPLICATION_UID) {
3876            return true;
3877        }
3878        if (mContext.checkCallingOrSelfPermission(
3879                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3880            return true;
3881        }
3882        if (mContext.checkCallingOrSelfPermission(
3883                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3884            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3885            if (homeComponent != null
3886                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3887                return true;
3888            }
3889        }
3890        return false;
3891    }
3892
3893    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3894        if (!sUserManager.exists(userId)) return null;
3895        if (ps == null) {
3896            return null;
3897        }
3898        final int callingUid = Binder.getCallingUid();
3899        // Filter out ephemeral app metadata:
3900        //   * The system/shell/root can see metadata for any app
3901        //   * An installed app can see metadata for 1) other installed apps
3902        //     and 2) ephemeral apps that have explicitly interacted with it
3903        //   * Ephemeral apps can only see their own data and exposed installed apps
3904        //   * Holding a signature permission allows seeing instant apps
3905        if (filterAppAccessLPr(ps, callingUid, userId)) {
3906            return null;
3907        }
3908
3909        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3910                && ps.isSystem()) {
3911            flags |= MATCH_ANY_USER;
3912        }
3913
3914        final PackageUserState state = ps.readUserState(userId);
3915        PackageParser.Package p = ps.pkg;
3916        if (p != null) {
3917            final PermissionsState permissionsState = ps.getPermissionsState();
3918
3919            // Compute GIDs only if requested
3920            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3921                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3922            // Compute granted permissions only if package has requested permissions
3923            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3924                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3925
3926            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3927                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3928
3929            if (packageInfo == null) {
3930                return null;
3931            }
3932
3933            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3934                    resolveExternalPackageNameLPr(p);
3935
3936            return packageInfo;
3937        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3938            PackageInfo pi = new PackageInfo();
3939            pi.packageName = ps.name;
3940            pi.setLongVersionCode(ps.versionCode);
3941            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3942            pi.firstInstallTime = ps.firstInstallTime;
3943            pi.lastUpdateTime = ps.lastUpdateTime;
3944
3945            ApplicationInfo ai = new ApplicationInfo();
3946            ai.packageName = ps.name;
3947            ai.uid = UserHandle.getUid(userId, ps.appId);
3948            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3949            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3950            ai.setVersionCode(ps.versionCode);
3951            ai.flags = ps.pkgFlags;
3952            ai.privateFlags = ps.pkgPrivateFlags;
3953            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3954
3955            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3956                    + ps.name + "]. Provides a minimum info.");
3957            return pi;
3958        } else {
3959            return null;
3960        }
3961    }
3962
3963    @Override
3964    public void checkPackageStartable(String packageName, int userId) {
3965        final int callingUid = Binder.getCallingUid();
3966        if (getInstantAppPackageName(callingUid) != null) {
3967            throw new SecurityException("Instant applications don't have access to this method");
3968        }
3969        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3970        synchronized (mPackages) {
3971            final PackageSetting ps = mSettings.mPackages.get(packageName);
3972            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3973                throw new SecurityException("Package " + packageName + " was not found!");
3974            }
3975
3976            if (!ps.getInstalled(userId)) {
3977                throw new SecurityException(
3978                        "Package " + packageName + " was not installed for user " + userId + "!");
3979            }
3980
3981            if (mSafeMode && !ps.isSystem()) {
3982                throw new SecurityException("Package " + packageName + " not a system app!");
3983            }
3984
3985            if (mFrozenPackages.contains(packageName)) {
3986                throw new SecurityException("Package " + packageName + " is currently frozen!");
3987            }
3988
3989            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3990                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3991            }
3992        }
3993    }
3994
3995    @Override
3996    public boolean isPackageAvailable(String packageName, int userId) {
3997        if (!sUserManager.exists(userId)) return false;
3998        final int callingUid = Binder.getCallingUid();
3999        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4000                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4001        synchronized (mPackages) {
4002            PackageParser.Package p = mPackages.get(packageName);
4003            if (p != null) {
4004                final PackageSetting ps = (PackageSetting) p.mExtras;
4005                if (filterAppAccessLPr(ps, callingUid, userId)) {
4006                    return false;
4007                }
4008                if (ps != null) {
4009                    final PackageUserState state = ps.readUserState(userId);
4010                    if (state != null) {
4011                        return PackageParser.isAvailable(state);
4012                    }
4013                }
4014            }
4015        }
4016        return false;
4017    }
4018
4019    @Override
4020    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4021        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4022                flags, Binder.getCallingUid(), userId);
4023    }
4024
4025    @Override
4026    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4027            int flags, int userId) {
4028        return getPackageInfoInternal(versionedPackage.getPackageName(),
4029                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4030    }
4031
4032    /**
4033     * Important: The provided filterCallingUid is used exclusively to filter out packages
4034     * that can be seen based on user state. It's typically the original caller uid prior
4035     * to clearing. Because it can only be provided by trusted code, it's value can be
4036     * trusted and will be used as-is; unlike userId which will be validated by this method.
4037     */
4038    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4039            int flags, int filterCallingUid, int userId) {
4040        if (!sUserManager.exists(userId)) return null;
4041        flags = updateFlagsForPackage(flags, userId, packageName);
4042        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4043                false /* requireFullPermission */, false /* checkShell */, "get package info");
4044
4045        // reader
4046        synchronized (mPackages) {
4047            // Normalize package name to handle renamed packages and static libs
4048            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4049
4050            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4051            if (matchFactoryOnly) {
4052                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4053                if (ps != null) {
4054                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4055                        return null;
4056                    }
4057                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4058                        return null;
4059                    }
4060                    return generatePackageInfo(ps, flags, userId);
4061                }
4062            }
4063
4064            PackageParser.Package p = mPackages.get(packageName);
4065            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4066                return null;
4067            }
4068            if (DEBUG_PACKAGE_INFO)
4069                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4070            if (p != null) {
4071                final PackageSetting ps = (PackageSetting) p.mExtras;
4072                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4073                    return null;
4074                }
4075                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4076                    return null;
4077                }
4078                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4079            }
4080            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4081                final PackageSetting ps = mSettings.mPackages.get(packageName);
4082                if (ps == null) return null;
4083                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4084                    return null;
4085                }
4086                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4087                    return null;
4088                }
4089                return generatePackageInfo(ps, flags, userId);
4090            }
4091        }
4092        return null;
4093    }
4094
4095    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4096        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4097            return true;
4098        }
4099        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4100            return true;
4101        }
4102        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4103            return true;
4104        }
4105        return false;
4106    }
4107
4108    private boolean isComponentVisibleToInstantApp(
4109            @Nullable ComponentName component, @ComponentType int type) {
4110        if (type == TYPE_ACTIVITY) {
4111            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4112            if (activity == null) {
4113                return false;
4114            }
4115            final boolean visibleToInstantApp =
4116                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4117            final boolean explicitlyVisibleToInstantApp =
4118                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4119            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4120        } else if (type == TYPE_RECEIVER) {
4121            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4122            if (activity == null) {
4123                return false;
4124            }
4125            final boolean visibleToInstantApp =
4126                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4127            final boolean explicitlyVisibleToInstantApp =
4128                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4129            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4130        } else if (type == TYPE_SERVICE) {
4131            final PackageParser.Service service = mServices.mServices.get(component);
4132            return service != null
4133                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4134                    : false;
4135        } else if (type == TYPE_PROVIDER) {
4136            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4137            return provider != null
4138                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4139                    : false;
4140        } else if (type == TYPE_UNKNOWN) {
4141            return isComponentVisibleToInstantApp(component);
4142        }
4143        return false;
4144    }
4145
4146    /**
4147     * Returns whether or not access to the application should be filtered.
4148     * <p>
4149     * Access may be limited based upon whether the calling or target applications
4150     * are instant applications.
4151     *
4152     * @see #canAccessInstantApps(int)
4153     */
4154    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4155            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4156        // if we're in an isolated process, get the real calling UID
4157        if (Process.isIsolated(callingUid)) {
4158            callingUid = mIsolatedOwners.get(callingUid);
4159        }
4160        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4161        final boolean callerIsInstantApp = instantAppPkgName != null;
4162        if (ps == null) {
4163            if (callerIsInstantApp) {
4164                // pretend the application exists, but, needs to be filtered
4165                return true;
4166            }
4167            return false;
4168        }
4169        // if the target and caller are the same application, don't filter
4170        if (isCallerSameApp(ps.name, callingUid)) {
4171            return false;
4172        }
4173        if (callerIsInstantApp) {
4174            // both caller and target are both instant, but, different applications, filter
4175            if (ps.getInstantApp(userId)) {
4176                return true;
4177            }
4178            // request for a specific component; if it hasn't been explicitly exposed through
4179            // property or instrumentation target, filter
4180            if (component != null) {
4181                final PackageParser.Instrumentation instrumentation =
4182                        mInstrumentation.get(component);
4183                if (instrumentation != null
4184                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4185                    return false;
4186                }
4187                return !isComponentVisibleToInstantApp(component, componentType);
4188            }
4189            // request for application; if no components have been explicitly exposed, filter
4190            return !ps.pkg.visibleToInstantApps;
4191        }
4192        if (ps.getInstantApp(userId)) {
4193            // caller can see all components of all instant applications, don't filter
4194            if (canViewInstantApps(callingUid, userId)) {
4195                return false;
4196            }
4197            // request for a specific instant application component, filter
4198            if (component != null) {
4199                return true;
4200            }
4201            // request for an instant application; if the caller hasn't been granted access, filter
4202            return !mInstantAppRegistry.isInstantAccessGranted(
4203                    userId, UserHandle.getAppId(callingUid), ps.appId);
4204        }
4205        return false;
4206    }
4207
4208    /**
4209     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4210     */
4211    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4212        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4213    }
4214
4215    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4216            int flags) {
4217        // Callers can access only the libs they depend on, otherwise they need to explicitly
4218        // ask for the shared libraries given the caller is allowed to access all static libs.
4219        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4220            // System/shell/root get to see all static libs
4221            final int appId = UserHandle.getAppId(uid);
4222            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4223                    || appId == Process.ROOT_UID) {
4224                return false;
4225            }
4226        }
4227
4228        // No package means no static lib as it is always on internal storage
4229        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4230            return false;
4231        }
4232
4233        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4234                ps.pkg.staticSharedLibVersion);
4235        if (libEntry == null) {
4236            return false;
4237        }
4238
4239        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4240        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4241        if (uidPackageNames == null) {
4242            return true;
4243        }
4244
4245        for (String uidPackageName : uidPackageNames) {
4246            if (ps.name.equals(uidPackageName)) {
4247                return false;
4248            }
4249            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4250            if (uidPs != null) {
4251                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4252                        libEntry.info.getName());
4253                if (index < 0) {
4254                    continue;
4255                }
4256                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4257                    return false;
4258                }
4259            }
4260        }
4261        return true;
4262    }
4263
4264    @Override
4265    public String[] currentToCanonicalPackageNames(String[] names) {
4266        final int callingUid = Binder.getCallingUid();
4267        if (getInstantAppPackageName(callingUid) != null) {
4268            return names;
4269        }
4270        final String[] out = new String[names.length];
4271        // reader
4272        synchronized (mPackages) {
4273            final int callingUserId = UserHandle.getUserId(callingUid);
4274            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4275            for (int i=names.length-1; i>=0; i--) {
4276                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4277                boolean translateName = false;
4278                if (ps != null && ps.realName != null) {
4279                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4280                    translateName = !targetIsInstantApp
4281                            || canViewInstantApps
4282                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4283                                    UserHandle.getAppId(callingUid), ps.appId);
4284                }
4285                out[i] = translateName ? ps.realName : names[i];
4286            }
4287        }
4288        return out;
4289    }
4290
4291    @Override
4292    public String[] canonicalToCurrentPackageNames(String[] names) {
4293        final int callingUid = Binder.getCallingUid();
4294        if (getInstantAppPackageName(callingUid) != null) {
4295            return names;
4296        }
4297        final String[] out = new String[names.length];
4298        // reader
4299        synchronized (mPackages) {
4300            final int callingUserId = UserHandle.getUserId(callingUid);
4301            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4302            for (int i=names.length-1; i>=0; i--) {
4303                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4304                boolean translateName = false;
4305                if (cur != null) {
4306                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4307                    final boolean targetIsInstantApp =
4308                            ps != null && ps.getInstantApp(callingUserId);
4309                    translateName = !targetIsInstantApp
4310                            || canViewInstantApps
4311                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4312                                    UserHandle.getAppId(callingUid), ps.appId);
4313                }
4314                out[i] = translateName ? cur : names[i];
4315            }
4316        }
4317        return out;
4318    }
4319
4320    @Override
4321    public int getPackageUid(String packageName, int flags, int userId) {
4322        if (!sUserManager.exists(userId)) return -1;
4323        final int callingUid = Binder.getCallingUid();
4324        flags = updateFlagsForPackage(flags, userId, packageName);
4325        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4326                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4327
4328        // reader
4329        synchronized (mPackages) {
4330            final PackageParser.Package p = mPackages.get(packageName);
4331            if (p != null && p.isMatch(flags)) {
4332                PackageSetting ps = (PackageSetting) p.mExtras;
4333                if (filterAppAccessLPr(ps, callingUid, userId)) {
4334                    return -1;
4335                }
4336                return UserHandle.getUid(userId, p.applicationInfo.uid);
4337            }
4338            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4339                final PackageSetting ps = mSettings.mPackages.get(packageName);
4340                if (ps != null && ps.isMatch(flags)
4341                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4342                    return UserHandle.getUid(userId, ps.appId);
4343                }
4344            }
4345        }
4346
4347        return -1;
4348    }
4349
4350    @Override
4351    public int[] getPackageGids(String packageName, int flags, int userId) {
4352        if (!sUserManager.exists(userId)) return null;
4353        final int callingUid = Binder.getCallingUid();
4354        flags = updateFlagsForPackage(flags, userId, packageName);
4355        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4356                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4357
4358        // reader
4359        synchronized (mPackages) {
4360            final PackageParser.Package p = mPackages.get(packageName);
4361            if (p != null && p.isMatch(flags)) {
4362                PackageSetting ps = (PackageSetting) p.mExtras;
4363                if (filterAppAccessLPr(ps, callingUid, userId)) {
4364                    return null;
4365                }
4366                // TODO: Shouldn't this be checking for package installed state for userId and
4367                // return null?
4368                return ps.getPermissionsState().computeGids(userId);
4369            }
4370            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4371                final PackageSetting ps = mSettings.mPackages.get(packageName);
4372                if (ps != null && ps.isMatch(flags)
4373                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4374                    return ps.getPermissionsState().computeGids(userId);
4375                }
4376            }
4377        }
4378
4379        return null;
4380    }
4381
4382    @Override
4383    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4384        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4385    }
4386
4387    @Override
4388    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4389            int flags) {
4390        final List<PermissionInfo> permissionList =
4391                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4392        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4393    }
4394
4395    @Override
4396    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4397        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4398    }
4399
4400    @Override
4401    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4402        final List<PermissionGroupInfo> permissionList =
4403                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4404        return (permissionList == null)
4405                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4406    }
4407
4408    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4409            int filterCallingUid, int userId) {
4410        if (!sUserManager.exists(userId)) return null;
4411        PackageSetting ps = mSettings.mPackages.get(packageName);
4412        if (ps != null) {
4413            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4414                return null;
4415            }
4416            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4417                return null;
4418            }
4419            if (ps.pkg == null) {
4420                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4421                if (pInfo != null) {
4422                    return pInfo.applicationInfo;
4423                }
4424                return null;
4425            }
4426            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4427                    ps.readUserState(userId), userId);
4428            if (ai != null) {
4429                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4430            }
4431            return ai;
4432        }
4433        return null;
4434    }
4435
4436    @Override
4437    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4438        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4439    }
4440
4441    /**
4442     * Important: The provided filterCallingUid is used exclusively to filter out applications
4443     * that can be seen based on user state. It's typically the original caller uid prior
4444     * to clearing. Because it can only be provided by trusted code, it's value can be
4445     * trusted and will be used as-is; unlike userId which will be validated by this method.
4446     */
4447    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4448            int filterCallingUid, int userId) {
4449        if (!sUserManager.exists(userId)) return null;
4450        flags = updateFlagsForApplication(flags, userId, packageName);
4451        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4452                false /* requireFullPermission */, false /* checkShell */, "get application info");
4453
4454        // writer
4455        synchronized (mPackages) {
4456            // Normalize package name to handle renamed packages and static libs
4457            packageName = resolveInternalPackageNameLPr(packageName,
4458                    PackageManager.VERSION_CODE_HIGHEST);
4459
4460            PackageParser.Package p = mPackages.get(packageName);
4461            if (DEBUG_PACKAGE_INFO) Log.v(
4462                    TAG, "getApplicationInfo " + packageName
4463                    + ": " + p);
4464            if (p != null) {
4465                PackageSetting ps = mSettings.mPackages.get(packageName);
4466                if (ps == null) return null;
4467                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4468                    return null;
4469                }
4470                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4471                    return null;
4472                }
4473                // Note: isEnabledLP() does not apply here - always return info
4474                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4475                        p, flags, ps.readUserState(userId), userId);
4476                if (ai != null) {
4477                    ai.packageName = resolveExternalPackageNameLPr(p);
4478                }
4479                return ai;
4480            }
4481            if ("android".equals(packageName)||"system".equals(packageName)) {
4482                return mAndroidApplication;
4483            }
4484            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4485                // Already generates the external package name
4486                return generateApplicationInfoFromSettingsLPw(packageName,
4487                        flags, filterCallingUid, userId);
4488            }
4489        }
4490        return null;
4491    }
4492
4493    private String normalizePackageNameLPr(String packageName) {
4494        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4495        return normalizedPackageName != null ? normalizedPackageName : packageName;
4496    }
4497
4498    @Override
4499    public void deletePreloadsFileCache() {
4500        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4501            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4502        }
4503        File dir = Environment.getDataPreloadsFileCacheDirectory();
4504        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4505        FileUtils.deleteContents(dir);
4506    }
4507
4508    @Override
4509    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4510            final int storageFlags, final IPackageDataObserver observer) {
4511        mContext.enforceCallingOrSelfPermission(
4512                android.Manifest.permission.CLEAR_APP_CACHE, null);
4513        mHandler.post(() -> {
4514            boolean success = false;
4515            try {
4516                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4517                success = true;
4518            } catch (IOException e) {
4519                Slog.w(TAG, e);
4520            }
4521            if (observer != null) {
4522                try {
4523                    observer.onRemoveCompleted(null, success);
4524                } catch (RemoteException e) {
4525                    Slog.w(TAG, e);
4526                }
4527            }
4528        });
4529    }
4530
4531    @Override
4532    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4533            final int storageFlags, final IntentSender pi) {
4534        mContext.enforceCallingOrSelfPermission(
4535                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4536        mHandler.post(() -> {
4537            boolean success = false;
4538            try {
4539                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4540                success = true;
4541            } catch (IOException e) {
4542                Slog.w(TAG, e);
4543            }
4544            if (pi != null) {
4545                try {
4546                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4547                } catch (SendIntentException e) {
4548                    Slog.w(TAG, e);
4549                }
4550            }
4551        });
4552    }
4553
4554    /**
4555     * Blocking call to clear various types of cached data across the system
4556     * until the requested bytes are available.
4557     */
4558    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4559        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4560        final File file = storage.findPathForUuid(volumeUuid);
4561        if (file.getUsableSpace() >= bytes) return;
4562
4563        if (ENABLE_FREE_CACHE_V2) {
4564            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4565                    volumeUuid);
4566            final boolean aggressive = (storageFlags
4567                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4568            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4569
4570            // 1. Pre-flight to determine if we have any chance to succeed
4571            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4572            if (internalVolume && (aggressive || SystemProperties
4573                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4574                deletePreloadsFileCache();
4575                if (file.getUsableSpace() >= bytes) return;
4576            }
4577
4578            // 3. Consider parsed APK data (aggressive only)
4579            if (internalVolume && aggressive) {
4580                FileUtils.deleteContents(mCacheDir);
4581                if (file.getUsableSpace() >= bytes) return;
4582            }
4583
4584            // 4. Consider cached app data (above quotas)
4585            try {
4586                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4587                        Installer.FLAG_FREE_CACHE_V2);
4588            } catch (InstallerException ignored) {
4589            }
4590            if (file.getUsableSpace() >= bytes) return;
4591
4592            // 5. Consider shared libraries with refcount=0 and age>min cache period
4593            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4594                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4595                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4596                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4597                return;
4598            }
4599
4600            // 6. Consider dexopt output (aggressive only)
4601            // TODO: Implement
4602
4603            // 7. Consider installed instant apps unused longer than min cache period
4604            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4605                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4606                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4607                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4608                return;
4609            }
4610
4611            // 8. Consider cached app data (below quotas)
4612            try {
4613                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4614                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4615            } catch (InstallerException ignored) {
4616            }
4617            if (file.getUsableSpace() >= bytes) return;
4618
4619            // 9. Consider DropBox entries
4620            // TODO: Implement
4621
4622            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4623            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4624                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4625                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4626                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4627                return;
4628            }
4629        } else {
4630            try {
4631                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4632            } catch (InstallerException ignored) {
4633            }
4634            if (file.getUsableSpace() >= bytes) return;
4635        }
4636
4637        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4638    }
4639
4640    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4641            throws IOException {
4642        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4643        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4644
4645        List<VersionedPackage> packagesToDelete = null;
4646        final long now = System.currentTimeMillis();
4647
4648        synchronized (mPackages) {
4649            final int[] allUsers = sUserManager.getUserIds();
4650            final int libCount = mSharedLibraries.size();
4651            for (int i = 0; i < libCount; i++) {
4652                final LongSparseArray<SharedLibraryEntry> versionedLib
4653                        = mSharedLibraries.valueAt(i);
4654                if (versionedLib == null) {
4655                    continue;
4656                }
4657                final int versionCount = versionedLib.size();
4658                for (int j = 0; j < versionCount; j++) {
4659                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4660                    // Skip packages that are not static shared libs.
4661                    if (!libInfo.isStatic()) {
4662                        break;
4663                    }
4664                    // Important: We skip static shared libs used for some user since
4665                    // in such a case we need to keep the APK on the device. The check for
4666                    // a lib being used for any user is performed by the uninstall call.
4667                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4668                    // Resolve the package name - we use synthetic package names internally
4669                    final String internalPackageName = resolveInternalPackageNameLPr(
4670                            declaringPackage.getPackageName(),
4671                            declaringPackage.getLongVersionCode());
4672                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4673                    // Skip unused static shared libs cached less than the min period
4674                    // to prevent pruning a lib needed by a subsequently installed package.
4675                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4676                        continue;
4677                    }
4678                    if (packagesToDelete == null) {
4679                        packagesToDelete = new ArrayList<>();
4680                    }
4681                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4682                            declaringPackage.getLongVersionCode()));
4683                }
4684            }
4685        }
4686
4687        if (packagesToDelete != null) {
4688            final int packageCount = packagesToDelete.size();
4689            for (int i = 0; i < packageCount; i++) {
4690                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4691                // Delete the package synchronously (will fail of the lib used for any user).
4692                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4693                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4694                                == PackageManager.DELETE_SUCCEEDED) {
4695                    if (volume.getUsableSpace() >= neededSpace) {
4696                        return true;
4697                    }
4698                }
4699            }
4700        }
4701
4702        return false;
4703    }
4704
4705    /**
4706     * Update given flags based on encryption status of current user.
4707     */
4708    private int updateFlags(int flags, int userId) {
4709        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4710                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4711            // Caller expressed an explicit opinion about what encryption
4712            // aware/unaware components they want to see, so fall through and
4713            // give them what they want
4714        } else {
4715            // Caller expressed no opinion, so match based on user state
4716            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4717                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4718            } else {
4719                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4720            }
4721        }
4722        return flags;
4723    }
4724
4725    private UserManagerInternal getUserManagerInternal() {
4726        if (mUserManagerInternal == null) {
4727            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4728        }
4729        return mUserManagerInternal;
4730    }
4731
4732    private ActivityManagerInternal getActivityManagerInternal() {
4733        if (mActivityManagerInternal == null) {
4734            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4735        }
4736        return mActivityManagerInternal;
4737    }
4738
4739
4740    private DeviceIdleController.LocalService getDeviceIdleController() {
4741        if (mDeviceIdleController == null) {
4742            mDeviceIdleController =
4743                    LocalServices.getService(DeviceIdleController.LocalService.class);
4744        }
4745        return mDeviceIdleController;
4746    }
4747
4748    /**
4749     * Update given flags when being used to request {@link PackageInfo}.
4750     */
4751    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4752        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4753        boolean triaged = true;
4754        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4755                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4756            // Caller is asking for component details, so they'd better be
4757            // asking for specific encryption matching behavior, or be triaged
4758            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4759                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4760                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4761                triaged = false;
4762            }
4763        }
4764        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4765                | PackageManager.MATCH_SYSTEM_ONLY
4766                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4767            triaged = false;
4768        }
4769        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4770            mPermissionManager.enforceCrossUserPermission(
4771                    Binder.getCallingUid(), userId, false, false,
4772                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4773                    + Debug.getCallers(5));
4774        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4775                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4776            // If the caller wants all packages and has a restricted profile associated with it,
4777            // then match all users. This is to make sure that launchers that need to access work
4778            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4779            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4780            flags |= PackageManager.MATCH_ANY_USER;
4781        }
4782        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4783            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4784                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4785        }
4786        return updateFlags(flags, userId);
4787    }
4788
4789    /**
4790     * Update given flags when being used to request {@link ApplicationInfo}.
4791     */
4792    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4793        return updateFlagsForPackage(flags, userId, cookie);
4794    }
4795
4796    /**
4797     * Update given flags when being used to request {@link ComponentInfo}.
4798     */
4799    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4800        if (cookie instanceof Intent) {
4801            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4802                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4803            }
4804        }
4805
4806        boolean triaged = true;
4807        // Caller is asking for component details, so they'd better be
4808        // asking for specific encryption matching behavior, or be triaged
4809        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4810                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4811                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4812            triaged = false;
4813        }
4814        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4815            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4816                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4817        }
4818
4819        return updateFlags(flags, userId);
4820    }
4821
4822    /**
4823     * Update given intent when being used to request {@link ResolveInfo}.
4824     */
4825    private Intent updateIntentForResolve(Intent intent) {
4826        if (intent.getSelector() != null) {
4827            intent = intent.getSelector();
4828        }
4829        if (DEBUG_PREFERRED) {
4830            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4831        }
4832        return intent;
4833    }
4834
4835    /**
4836     * Update given flags when being used to request {@link ResolveInfo}.
4837     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4838     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4839     * flag set. However, this flag is only honoured in three circumstances:
4840     * <ul>
4841     * <li>when called from a system process</li>
4842     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4843     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4844     * action and a {@code android.intent.category.BROWSABLE} category</li>
4845     * </ul>
4846     */
4847    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4848        return updateFlagsForResolve(flags, userId, intent, callingUid,
4849                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4850    }
4851    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4852            boolean wantInstantApps) {
4853        return updateFlagsForResolve(flags, userId, intent, callingUid,
4854                wantInstantApps, false /*onlyExposedExplicitly*/);
4855    }
4856    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4857            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4858        // Safe mode means we shouldn't match any third-party components
4859        if (mSafeMode) {
4860            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4861        }
4862        if (getInstantAppPackageName(callingUid) != null) {
4863            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4864            if (onlyExposedExplicitly) {
4865                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4866            }
4867            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4868            flags |= PackageManager.MATCH_INSTANT;
4869        } else {
4870            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4871            final boolean allowMatchInstant = wantInstantApps
4872                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4873            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4874                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4875            if (!allowMatchInstant) {
4876                flags &= ~PackageManager.MATCH_INSTANT;
4877            }
4878        }
4879        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4880    }
4881
4882    @Override
4883    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4884        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4885    }
4886
4887    /**
4888     * Important: The provided filterCallingUid is used exclusively to filter out activities
4889     * that can be seen based on user state. It's typically the original caller uid prior
4890     * to clearing. Because it can only be provided by trusted code, it's value can be
4891     * trusted and will be used as-is; unlike userId which will be validated by this method.
4892     */
4893    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4894            int filterCallingUid, int userId) {
4895        if (!sUserManager.exists(userId)) return null;
4896        flags = updateFlagsForComponent(flags, userId, component);
4897
4898        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4899            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4900                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4901        }
4902
4903        synchronized (mPackages) {
4904            PackageParser.Activity a = mActivities.mActivities.get(component);
4905
4906            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4907            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4908                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4909                if (ps == null) return null;
4910                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4911                    return null;
4912                }
4913                return PackageParser.generateActivityInfo(
4914                        a, flags, ps.readUserState(userId), userId);
4915            }
4916            if (mResolveComponentName.equals(component)) {
4917                return PackageParser.generateActivityInfo(
4918                        mResolveActivity, flags, new PackageUserState(), userId);
4919            }
4920        }
4921        return null;
4922    }
4923
4924    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4925        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4926            return false;
4927        }
4928        final long token = Binder.clearCallingIdentity();
4929        try {
4930            final int callingUserId = UserHandle.getUserId(callingUid);
4931            if (ActivityManager.getCurrentUser() != callingUserId) {
4932                return false;
4933            }
4934            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4935        } finally {
4936            Binder.restoreCallingIdentity(token);
4937        }
4938    }
4939
4940    @Override
4941    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4942            String resolvedType) {
4943        synchronized (mPackages) {
4944            if (component.equals(mResolveComponentName)) {
4945                // The resolver supports EVERYTHING!
4946                return true;
4947            }
4948            final int callingUid = Binder.getCallingUid();
4949            final int callingUserId = UserHandle.getUserId(callingUid);
4950            PackageParser.Activity a = mActivities.mActivities.get(component);
4951            if (a == null) {
4952                return false;
4953            }
4954            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4955            if (ps == null) {
4956                return false;
4957            }
4958            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4959                return false;
4960            }
4961            for (int i=0; i<a.intents.size(); i++) {
4962                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4963                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4964                    return true;
4965                }
4966            }
4967            return false;
4968        }
4969    }
4970
4971    @Override
4972    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4973        if (!sUserManager.exists(userId)) return null;
4974        final int callingUid = Binder.getCallingUid();
4975        flags = updateFlagsForComponent(flags, userId, component);
4976        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4977                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4978        synchronized (mPackages) {
4979            PackageParser.Activity a = mReceivers.mActivities.get(component);
4980            if (DEBUG_PACKAGE_INFO) Log.v(
4981                TAG, "getReceiverInfo " + component + ": " + a);
4982            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4983                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4984                if (ps == null) return null;
4985                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4986                    return null;
4987                }
4988                return PackageParser.generateActivityInfo(
4989                        a, flags, ps.readUserState(userId), userId);
4990            }
4991        }
4992        return null;
4993    }
4994
4995    @Override
4996    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4997            int flags, int userId) {
4998        if (!sUserManager.exists(userId)) return null;
4999        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5000        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5001            return null;
5002        }
5003
5004        flags = updateFlagsForPackage(flags, userId, null);
5005
5006        final boolean canSeeStaticLibraries =
5007                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5008                        == PERMISSION_GRANTED
5009                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5010                        == PERMISSION_GRANTED
5011                || canRequestPackageInstallsInternal(packageName,
5012                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5013                        false  /* throwIfPermNotDeclared*/)
5014                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5015                        == PERMISSION_GRANTED;
5016
5017        synchronized (mPackages) {
5018            List<SharedLibraryInfo> result = null;
5019
5020            final int libCount = mSharedLibraries.size();
5021            for (int i = 0; i < libCount; i++) {
5022                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5023                if (versionedLib == null) {
5024                    continue;
5025                }
5026
5027                final int versionCount = versionedLib.size();
5028                for (int j = 0; j < versionCount; j++) {
5029                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5030                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5031                        break;
5032                    }
5033                    final long identity = Binder.clearCallingIdentity();
5034                    try {
5035                        PackageInfo packageInfo = getPackageInfoVersioned(
5036                                libInfo.getDeclaringPackage(), flags
5037                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5038                        if (packageInfo == null) {
5039                            continue;
5040                        }
5041                    } finally {
5042                        Binder.restoreCallingIdentity(identity);
5043                    }
5044
5045                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5046                            libInfo.getLongVersion(), libInfo.getType(),
5047                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5048                            flags, userId));
5049
5050                    if (result == null) {
5051                        result = new ArrayList<>();
5052                    }
5053                    result.add(resLibInfo);
5054                }
5055            }
5056
5057            return result != null ? new ParceledListSlice<>(result) : null;
5058        }
5059    }
5060
5061    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5062            SharedLibraryInfo libInfo, int flags, int userId) {
5063        List<VersionedPackage> versionedPackages = null;
5064        final int packageCount = mSettings.mPackages.size();
5065        for (int i = 0; i < packageCount; i++) {
5066            PackageSetting ps = mSettings.mPackages.valueAt(i);
5067
5068            if (ps == null) {
5069                continue;
5070            }
5071
5072            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5073                continue;
5074            }
5075
5076            final String libName = libInfo.getName();
5077            if (libInfo.isStatic()) {
5078                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5079                if (libIdx < 0) {
5080                    continue;
5081                }
5082                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5083                    continue;
5084                }
5085                if (versionedPackages == null) {
5086                    versionedPackages = new ArrayList<>();
5087                }
5088                // If the dependent is a static shared lib, use the public package name
5089                String dependentPackageName = ps.name;
5090                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5091                    dependentPackageName = ps.pkg.manifestPackageName;
5092                }
5093                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5094            } else if (ps.pkg != null) {
5095                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5096                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5097                    if (versionedPackages == null) {
5098                        versionedPackages = new ArrayList<>();
5099                    }
5100                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5101                }
5102            }
5103        }
5104
5105        return versionedPackages;
5106    }
5107
5108    @Override
5109    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5110        if (!sUserManager.exists(userId)) return null;
5111        final int callingUid = Binder.getCallingUid();
5112        flags = updateFlagsForComponent(flags, userId, component);
5113        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5114                false /* requireFullPermission */, false /* checkShell */, "get service info");
5115        synchronized (mPackages) {
5116            PackageParser.Service s = mServices.mServices.get(component);
5117            if (DEBUG_PACKAGE_INFO) Log.v(
5118                TAG, "getServiceInfo " + component + ": " + s);
5119            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5120                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5121                if (ps == null) return null;
5122                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5123                    return null;
5124                }
5125                return PackageParser.generateServiceInfo(
5126                        s, flags, ps.readUserState(userId), userId);
5127            }
5128        }
5129        return null;
5130    }
5131
5132    @Override
5133    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5134        if (!sUserManager.exists(userId)) return null;
5135        final int callingUid = Binder.getCallingUid();
5136        flags = updateFlagsForComponent(flags, userId, component);
5137        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5138                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5139        synchronized (mPackages) {
5140            PackageParser.Provider p = mProviders.mProviders.get(component);
5141            if (DEBUG_PACKAGE_INFO) Log.v(
5142                TAG, "getProviderInfo " + component + ": " + p);
5143            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5144                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5145                if (ps == null) return null;
5146                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5147                    return null;
5148                }
5149                return PackageParser.generateProviderInfo(
5150                        p, flags, ps.readUserState(userId), userId);
5151            }
5152        }
5153        return null;
5154    }
5155
5156    @Override
5157    public String[] getSystemSharedLibraryNames() {
5158        // allow instant applications
5159        synchronized (mPackages) {
5160            Set<String> libs = null;
5161            final int libCount = mSharedLibraries.size();
5162            for (int i = 0; i < libCount; i++) {
5163                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5164                if (versionedLib == null) {
5165                    continue;
5166                }
5167                final int versionCount = versionedLib.size();
5168                for (int j = 0; j < versionCount; j++) {
5169                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5170                    if (!libEntry.info.isStatic()) {
5171                        if (libs == null) {
5172                            libs = new ArraySet<>();
5173                        }
5174                        libs.add(libEntry.info.getName());
5175                        break;
5176                    }
5177                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5178                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5179                            UserHandle.getUserId(Binder.getCallingUid()),
5180                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5181                        if (libs == null) {
5182                            libs = new ArraySet<>();
5183                        }
5184                        libs.add(libEntry.info.getName());
5185                        break;
5186                    }
5187                }
5188            }
5189
5190            if (libs != null) {
5191                String[] libsArray = new String[libs.size()];
5192                libs.toArray(libsArray);
5193                return libsArray;
5194            }
5195
5196            return null;
5197        }
5198    }
5199
5200    @Override
5201    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5202        // allow instant applications
5203        synchronized (mPackages) {
5204            return mServicesSystemSharedLibraryPackageName;
5205        }
5206    }
5207
5208    @Override
5209    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5210        // allow instant applications
5211        synchronized (mPackages) {
5212            return mSharedSystemSharedLibraryPackageName;
5213        }
5214    }
5215
5216    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5217        for (int i = userList.length - 1; i >= 0; --i) {
5218            final int userId = userList[i];
5219            // don't add instant app to the list of updates
5220            if (pkgSetting.getInstantApp(userId)) {
5221                continue;
5222            }
5223            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5224            if (changedPackages == null) {
5225                changedPackages = new SparseArray<>();
5226                mChangedPackages.put(userId, changedPackages);
5227            }
5228            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5229            if (sequenceNumbers == null) {
5230                sequenceNumbers = new HashMap<>();
5231                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5232            }
5233            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5234            if (sequenceNumber != null) {
5235                changedPackages.remove(sequenceNumber);
5236            }
5237            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5238            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5239        }
5240        mChangedPackagesSequenceNumber++;
5241    }
5242
5243    @Override
5244    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5245        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5246            return null;
5247        }
5248        synchronized (mPackages) {
5249            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5250                return null;
5251            }
5252            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5253            if (changedPackages == null) {
5254                return null;
5255            }
5256            final List<String> packageNames =
5257                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5258            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5259                final String packageName = changedPackages.get(i);
5260                if (packageName != null) {
5261                    packageNames.add(packageName);
5262                }
5263            }
5264            return packageNames.isEmpty()
5265                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5266        }
5267    }
5268
5269    @Override
5270    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5271        // allow instant applications
5272        ArrayList<FeatureInfo> res;
5273        synchronized (mAvailableFeatures) {
5274            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5275            res.addAll(mAvailableFeatures.values());
5276        }
5277        final FeatureInfo fi = new FeatureInfo();
5278        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5279                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5280        res.add(fi);
5281
5282        return new ParceledListSlice<>(res);
5283    }
5284
5285    @Override
5286    public boolean hasSystemFeature(String name, int version) {
5287        // allow instant applications
5288        synchronized (mAvailableFeatures) {
5289            final FeatureInfo feat = mAvailableFeatures.get(name);
5290            if (feat == null) {
5291                return false;
5292            } else {
5293                return feat.version >= version;
5294            }
5295        }
5296    }
5297
5298    @Override
5299    public int checkPermission(String permName, String pkgName, int userId) {
5300        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5301    }
5302
5303    @Override
5304    public int checkUidPermission(String permName, int uid) {
5305        synchronized (mPackages) {
5306            final String[] packageNames = getPackagesForUid(uid);
5307            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5308                    ? mSettings.getPackageLPr(packageNames[0]).getPackage()
5309                    : null;
5310            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5311        }
5312    }
5313
5314    @Override
5315    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5316        if (UserHandle.getCallingUserId() != userId) {
5317            mContext.enforceCallingPermission(
5318                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5319                    "isPermissionRevokedByPolicy for user " + userId);
5320        }
5321
5322        if (checkPermission(permission, packageName, userId)
5323                == PackageManager.PERMISSION_GRANTED) {
5324            return false;
5325        }
5326
5327        final int callingUid = Binder.getCallingUid();
5328        if (getInstantAppPackageName(callingUid) != null) {
5329            if (!isCallerSameApp(packageName, callingUid)) {
5330                return false;
5331            }
5332        } else {
5333            if (isInstantApp(packageName, userId)) {
5334                return false;
5335            }
5336        }
5337
5338        final long identity = Binder.clearCallingIdentity();
5339        try {
5340            final int flags = getPermissionFlags(permission, packageName, userId);
5341            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5342        } finally {
5343            Binder.restoreCallingIdentity(identity);
5344        }
5345    }
5346
5347    @Override
5348    public String getPermissionControllerPackageName() {
5349        synchronized (mPackages) {
5350            return mRequiredInstallerPackage;
5351        }
5352    }
5353
5354    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5355        return mPermissionManager.addDynamicPermission(
5356                info, async, getCallingUid(), new PermissionCallback() {
5357                    @Override
5358                    public void onPermissionChanged() {
5359                        if (!async) {
5360                            mSettings.writeLPr();
5361                        } else {
5362                            scheduleWriteSettingsLocked();
5363                        }
5364                    }
5365                });
5366    }
5367
5368    @Override
5369    public boolean addPermission(PermissionInfo info) {
5370        synchronized (mPackages) {
5371            return addDynamicPermission(info, false);
5372        }
5373    }
5374
5375    @Override
5376    public boolean addPermissionAsync(PermissionInfo info) {
5377        synchronized (mPackages) {
5378            return addDynamicPermission(info, true);
5379        }
5380    }
5381
5382    @Override
5383    public void removePermission(String permName) {
5384        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5385    }
5386
5387    @Override
5388    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5389        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5390                getCallingUid(), userId, mPermissionCallback);
5391    }
5392
5393    @Override
5394    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5395        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5396                getCallingUid(), userId, mPermissionCallback);
5397    }
5398
5399    @Override
5400    public void resetRuntimePermissions() {
5401        mContext.enforceCallingOrSelfPermission(
5402                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5403                "revokeRuntimePermission");
5404
5405        int callingUid = Binder.getCallingUid();
5406        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5407            mContext.enforceCallingOrSelfPermission(
5408                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5409                    "resetRuntimePermissions");
5410        }
5411
5412        synchronized (mPackages) {
5413            mPermissionManager.updateAllPermissions(
5414                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5415                    mPermissionCallback);
5416            for (int userId : UserManagerService.getInstance().getUserIds()) {
5417                final int packageCount = mPackages.size();
5418                for (int i = 0; i < packageCount; i++) {
5419                    PackageParser.Package pkg = mPackages.valueAt(i);
5420                    if (!(pkg.mExtras instanceof PackageSetting)) {
5421                        continue;
5422                    }
5423                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5424                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5425                }
5426            }
5427        }
5428    }
5429
5430    @Override
5431    public int getPermissionFlags(String permName, String packageName, int userId) {
5432        return mPermissionManager.getPermissionFlags(
5433                permName, packageName, getCallingUid(), userId);
5434    }
5435
5436    @Override
5437    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5438            int flagValues, int userId) {
5439        mPermissionManager.updatePermissionFlags(
5440                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5441                mPermissionCallback);
5442    }
5443
5444    /**
5445     * Update the permission flags for all packages and runtime permissions of a user in order
5446     * to allow device or profile owner to remove POLICY_FIXED.
5447     */
5448    @Override
5449    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5450        synchronized (mPackages) {
5451            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5452                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5453                    mPermissionCallback);
5454            if (changed) {
5455                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5456            }
5457        }
5458    }
5459
5460    @Override
5461    public boolean shouldShowRequestPermissionRationale(String permissionName,
5462            String packageName, int userId) {
5463        if (UserHandle.getCallingUserId() != userId) {
5464            mContext.enforceCallingPermission(
5465                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5466                    "canShowRequestPermissionRationale for user " + userId);
5467        }
5468
5469        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5470        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5471            return false;
5472        }
5473
5474        if (checkPermission(permissionName, packageName, userId)
5475                == PackageManager.PERMISSION_GRANTED) {
5476            return false;
5477        }
5478
5479        final int flags;
5480
5481        final long identity = Binder.clearCallingIdentity();
5482        try {
5483            flags = getPermissionFlags(permissionName,
5484                    packageName, userId);
5485        } finally {
5486            Binder.restoreCallingIdentity(identity);
5487        }
5488
5489        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5490                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5491                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5492
5493        if ((flags & fixedFlags) != 0) {
5494            return false;
5495        }
5496
5497        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5498    }
5499
5500    @Override
5501    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5502        mContext.enforceCallingOrSelfPermission(
5503                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5504                "addOnPermissionsChangeListener");
5505
5506        synchronized (mPackages) {
5507            mOnPermissionChangeListeners.addListenerLocked(listener);
5508        }
5509    }
5510
5511    @Override
5512    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5514            throw new SecurityException("Instant applications don't have access to this method");
5515        }
5516        synchronized (mPackages) {
5517            mOnPermissionChangeListeners.removeListenerLocked(listener);
5518        }
5519    }
5520
5521    @Override
5522    public boolean isProtectedBroadcast(String actionName) {
5523        // allow instant applications
5524        synchronized (mProtectedBroadcasts) {
5525            if (mProtectedBroadcasts.contains(actionName)) {
5526                return true;
5527            } else if (actionName != null) {
5528                // TODO: remove these terrible hacks
5529                if (actionName.startsWith("android.net.netmon.lingerExpired")
5530                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5531                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5532                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5533                    return true;
5534                }
5535            }
5536        }
5537        return false;
5538    }
5539
5540    @Override
5541    public int checkSignatures(String pkg1, String pkg2) {
5542        synchronized (mPackages) {
5543            final PackageParser.Package p1 = mPackages.get(pkg1);
5544            final PackageParser.Package p2 = mPackages.get(pkg2);
5545            if (p1 == null || p1.mExtras == null
5546                    || p2 == null || p2.mExtras == null) {
5547                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5548            }
5549            final int callingUid = Binder.getCallingUid();
5550            final int callingUserId = UserHandle.getUserId(callingUid);
5551            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5552            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5553            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5554                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5555                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5556            }
5557            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5558        }
5559    }
5560
5561    @Override
5562    public int checkUidSignatures(int uid1, int uid2) {
5563        final int callingUid = Binder.getCallingUid();
5564        final int callingUserId = UserHandle.getUserId(callingUid);
5565        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5566        // Map to base uids.
5567        uid1 = UserHandle.getAppId(uid1);
5568        uid2 = UserHandle.getAppId(uid2);
5569        // reader
5570        synchronized (mPackages) {
5571            Signature[] s1;
5572            Signature[] s2;
5573            Object obj = mSettings.getUserIdLPr(uid1);
5574            if (obj != null) {
5575                if (obj instanceof SharedUserSetting) {
5576                    if (isCallerInstantApp) {
5577                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5578                    }
5579                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5580                } else if (obj instanceof PackageSetting) {
5581                    final PackageSetting ps = (PackageSetting) obj;
5582                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5583                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5584                    }
5585                    s1 = ps.signatures.mSigningDetails.signatures;
5586                } else {
5587                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5588                }
5589            } else {
5590                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5591            }
5592            obj = mSettings.getUserIdLPr(uid2);
5593            if (obj != null) {
5594                if (obj instanceof SharedUserSetting) {
5595                    if (isCallerInstantApp) {
5596                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5597                    }
5598                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5599                } else if (obj instanceof PackageSetting) {
5600                    final PackageSetting ps = (PackageSetting) obj;
5601                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5602                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5603                    }
5604                    s2 = ps.signatures.mSigningDetails.signatures;
5605                } else {
5606                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5607                }
5608            } else {
5609                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5610            }
5611            return compareSignatures(s1, s2);
5612        }
5613    }
5614
5615    @Override
5616    public boolean hasSigningCertificate(
5617            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5618
5619        synchronized (mPackages) {
5620            final PackageParser.Package p = mPackages.get(packageName);
5621            if (p == null || p.mExtras == null) {
5622                return false;
5623            }
5624            final int callingUid = Binder.getCallingUid();
5625            final int callingUserId = UserHandle.getUserId(callingUid);
5626            final PackageSetting ps = (PackageSetting) p.mExtras;
5627            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5628                return false;
5629            }
5630            switch (type) {
5631                case CERT_INPUT_RAW_X509:
5632                    return p.mSigningDetails.hasCertificate(certificate);
5633                case CERT_INPUT_SHA256:
5634                    return p.mSigningDetails.hasSha256Certificate(certificate);
5635                default:
5636                    return false;
5637            }
5638        }
5639    }
5640
5641    @Override
5642    public boolean hasUidSigningCertificate(
5643            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5644        final int callingUid = Binder.getCallingUid();
5645        final int callingUserId = UserHandle.getUserId(callingUid);
5646        // Map to base uids.
5647        uid = UserHandle.getAppId(uid);
5648        // reader
5649        synchronized (mPackages) {
5650            final PackageParser.SigningDetails signingDetails;
5651            final Object obj = mSettings.getUserIdLPr(uid);
5652            if (obj != null) {
5653                if (obj instanceof SharedUserSetting) {
5654                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5655                    if (isCallerInstantApp) {
5656                        return false;
5657                    }
5658                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5659                } else if (obj instanceof PackageSetting) {
5660                    final PackageSetting ps = (PackageSetting) obj;
5661                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5662                        return false;
5663                    }
5664                    signingDetails = ps.signatures.mSigningDetails;
5665                } else {
5666                    return false;
5667                }
5668            } else {
5669                return false;
5670            }
5671            switch (type) {
5672                case CERT_INPUT_RAW_X509:
5673                    return signingDetails.hasCertificate(certificate);
5674                case CERT_INPUT_SHA256:
5675                    return signingDetails.hasSha256Certificate(certificate);
5676                default:
5677                    return false;
5678            }
5679        }
5680    }
5681
5682    /**
5683     * This method should typically only be used when granting or revoking
5684     * permissions, since the app may immediately restart after this call.
5685     * <p>
5686     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5687     * guard your work against the app being relaunched.
5688     */
5689    private void killUid(int appId, int userId, String reason) {
5690        final long identity = Binder.clearCallingIdentity();
5691        try {
5692            IActivityManager am = ActivityManager.getService();
5693            if (am != null) {
5694                try {
5695                    am.killUid(appId, userId, reason);
5696                } catch (RemoteException e) {
5697                    /* ignore - same process */
5698                }
5699            }
5700        } finally {
5701            Binder.restoreCallingIdentity(identity);
5702        }
5703    }
5704
5705    /**
5706     * If the database version for this type of package (internal storage or
5707     * external storage) is less than the version where package signatures
5708     * were updated, return true.
5709     */
5710    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5711        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5712        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5713    }
5714
5715    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5716        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5717        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5718    }
5719
5720    @Override
5721    public List<String> getAllPackages() {
5722        final int callingUid = Binder.getCallingUid();
5723        final int callingUserId = UserHandle.getUserId(callingUid);
5724        synchronized (mPackages) {
5725            if (canViewInstantApps(callingUid, callingUserId)) {
5726                return new ArrayList<String>(mPackages.keySet());
5727            }
5728            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5729            final List<String> result = new ArrayList<>();
5730            if (instantAppPkgName != null) {
5731                // caller is an instant application; filter unexposed applications
5732                for (PackageParser.Package pkg : mPackages.values()) {
5733                    if (!pkg.visibleToInstantApps) {
5734                        continue;
5735                    }
5736                    result.add(pkg.packageName);
5737                }
5738            } else {
5739                // caller is a normal application; filter instant applications
5740                for (PackageParser.Package pkg : mPackages.values()) {
5741                    final PackageSetting ps =
5742                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5743                    if (ps != null
5744                            && ps.getInstantApp(callingUserId)
5745                            && !mInstantAppRegistry.isInstantAccessGranted(
5746                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5747                        continue;
5748                    }
5749                    result.add(pkg.packageName);
5750                }
5751            }
5752            return result;
5753        }
5754    }
5755
5756    @Override
5757    public String[] getPackagesForUid(int uid) {
5758        final int callingUid = Binder.getCallingUid();
5759        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5760        final int userId = UserHandle.getUserId(uid);
5761        uid = UserHandle.getAppId(uid);
5762        // reader
5763        synchronized (mPackages) {
5764            Object obj = mSettings.getUserIdLPr(uid);
5765            if (obj instanceof SharedUserSetting) {
5766                if (isCallerInstantApp) {
5767                    return null;
5768                }
5769                final SharedUserSetting sus = (SharedUserSetting) obj;
5770                final int N = sus.packages.size();
5771                String[] res = new String[N];
5772                final Iterator<PackageSetting> it = sus.packages.iterator();
5773                int i = 0;
5774                while (it.hasNext()) {
5775                    PackageSetting ps = it.next();
5776                    if (ps.getInstalled(userId)) {
5777                        res[i++] = ps.name;
5778                    } else {
5779                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5780                    }
5781                }
5782                return res;
5783            } else if (obj instanceof PackageSetting) {
5784                final PackageSetting ps = (PackageSetting) obj;
5785                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5786                    return new String[]{ps.name};
5787                }
5788            }
5789        }
5790        return null;
5791    }
5792
5793    @Override
5794    public String getNameForUid(int uid) {
5795        final int callingUid = Binder.getCallingUid();
5796        if (getInstantAppPackageName(callingUid) != null) {
5797            return null;
5798        }
5799        synchronized (mPackages) {
5800            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5801            if (obj instanceof SharedUserSetting) {
5802                final SharedUserSetting sus = (SharedUserSetting) obj;
5803                return sus.name + ":" + sus.userId;
5804            } else if (obj instanceof PackageSetting) {
5805                final PackageSetting ps = (PackageSetting) obj;
5806                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5807                    return null;
5808                }
5809                return ps.name;
5810            }
5811            return null;
5812        }
5813    }
5814
5815    @Override
5816    public String[] getNamesForUids(int[] uids) {
5817        if (uids == null || uids.length == 0) {
5818            return null;
5819        }
5820        final int callingUid = Binder.getCallingUid();
5821        if (getInstantAppPackageName(callingUid) != null) {
5822            return null;
5823        }
5824        final String[] names = new String[uids.length];
5825        synchronized (mPackages) {
5826            for (int i = uids.length - 1; i >= 0; i--) {
5827                final int uid = uids[i];
5828                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5829                if (obj instanceof SharedUserSetting) {
5830                    final SharedUserSetting sus = (SharedUserSetting) obj;
5831                    names[i] = "shared:" + sus.name;
5832                } else if (obj instanceof PackageSetting) {
5833                    final PackageSetting ps = (PackageSetting) obj;
5834                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5835                        names[i] = null;
5836                    } else {
5837                        names[i] = ps.name;
5838                    }
5839                } else {
5840                    names[i] = null;
5841                }
5842            }
5843        }
5844        return names;
5845    }
5846
5847    @Override
5848    public int getUidForSharedUser(String sharedUserName) {
5849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5850            return -1;
5851        }
5852        if (sharedUserName == null) {
5853            return -1;
5854        }
5855        // reader
5856        synchronized (mPackages) {
5857            SharedUserSetting suid;
5858            try {
5859                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5860                if (suid != null) {
5861                    return suid.userId;
5862                }
5863            } catch (PackageManagerException ignore) {
5864                // can't happen, but, still need to catch it
5865            }
5866            return -1;
5867        }
5868    }
5869
5870    @Override
5871    public int getFlagsForUid(int uid) {
5872        final int callingUid = Binder.getCallingUid();
5873        if (getInstantAppPackageName(callingUid) != null) {
5874            return 0;
5875        }
5876        synchronized (mPackages) {
5877            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5878            if (obj instanceof SharedUserSetting) {
5879                final SharedUserSetting sus = (SharedUserSetting) obj;
5880                return sus.pkgFlags;
5881            } else if (obj instanceof PackageSetting) {
5882                final PackageSetting ps = (PackageSetting) obj;
5883                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5884                    return 0;
5885                }
5886                return ps.pkgFlags;
5887            }
5888        }
5889        return 0;
5890    }
5891
5892    @Override
5893    public int getPrivateFlagsForUid(int uid) {
5894        final int callingUid = Binder.getCallingUid();
5895        if (getInstantAppPackageName(callingUid) != null) {
5896            return 0;
5897        }
5898        synchronized (mPackages) {
5899            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5900            if (obj instanceof SharedUserSetting) {
5901                final SharedUserSetting sus = (SharedUserSetting) obj;
5902                return sus.pkgPrivateFlags;
5903            } else if (obj instanceof PackageSetting) {
5904                final PackageSetting ps = (PackageSetting) obj;
5905                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5906                    return 0;
5907                }
5908                return ps.pkgPrivateFlags;
5909            }
5910        }
5911        return 0;
5912    }
5913
5914    @Override
5915    public boolean isUidPrivileged(int uid) {
5916        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5917            return false;
5918        }
5919        uid = UserHandle.getAppId(uid);
5920        // reader
5921        synchronized (mPackages) {
5922            Object obj = mSettings.getUserIdLPr(uid);
5923            if (obj instanceof SharedUserSetting) {
5924                final SharedUserSetting sus = (SharedUserSetting) obj;
5925                final Iterator<PackageSetting> it = sus.packages.iterator();
5926                while (it.hasNext()) {
5927                    if (it.next().isPrivileged()) {
5928                        return true;
5929                    }
5930                }
5931            } else if (obj instanceof PackageSetting) {
5932                final PackageSetting ps = (PackageSetting) obj;
5933                return ps.isPrivileged();
5934            }
5935        }
5936        return false;
5937    }
5938
5939    @Override
5940    public String[] getAppOpPermissionPackages(String permName) {
5941        return mPermissionManager.getAppOpPermissionPackages(permName);
5942    }
5943
5944    @Override
5945    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5946            int flags, int userId) {
5947        return resolveIntentInternal(intent, resolvedType, flags, userId, false,
5948                Binder.getCallingUid());
5949    }
5950
5951    /**
5952     * Normally instant apps can only be resolved when they're visible to the caller.
5953     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5954     * since we need to allow the system to start any installed application.
5955     */
5956    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5957            int flags, int userId, boolean resolveForStart, int filterCallingUid) {
5958        try {
5959            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5960
5961            if (!sUserManager.exists(userId)) return null;
5962            final int callingUid = Binder.getCallingUid();
5963            flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
5964            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5965                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5966
5967            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5968            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5969                    flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5970            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5971
5972            final ResolveInfo bestChoice =
5973                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5974            return bestChoice;
5975        } finally {
5976            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5977        }
5978    }
5979
5980    @Override
5981    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5982        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5983            throw new SecurityException(
5984                    "findPersistentPreferredActivity can only be run by the system");
5985        }
5986        if (!sUserManager.exists(userId)) {
5987            return null;
5988        }
5989        final int callingUid = Binder.getCallingUid();
5990        intent = updateIntentForResolve(intent);
5991        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5992        final int flags = updateFlagsForResolve(
5993                0, userId, intent, callingUid, false /*includeInstantApps*/);
5994        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5995                userId);
5996        synchronized (mPackages) {
5997            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5998                    userId);
5999        }
6000    }
6001
6002    @Override
6003    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6004            IntentFilter filter, int match, ComponentName activity) {
6005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6006            return;
6007        }
6008        final int userId = UserHandle.getCallingUserId();
6009        if (DEBUG_PREFERRED) {
6010            Log.v(TAG, "setLastChosenActivity intent=" + intent
6011                + " resolvedType=" + resolvedType
6012                + " flags=" + flags
6013                + " filter=" + filter
6014                + " match=" + match
6015                + " activity=" + activity);
6016            filter.dump(new PrintStreamPrinter(System.out), "    ");
6017        }
6018        intent.setComponent(null);
6019        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6020                userId);
6021        // Find any earlier preferred or last chosen entries and nuke them
6022        findPreferredActivity(intent, resolvedType,
6023                flags, query, 0, false, true, false, userId);
6024        // Add the new activity as the last chosen for this filter
6025        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6026                "Setting last chosen");
6027    }
6028
6029    @Override
6030    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6032            return null;
6033        }
6034        final int userId = UserHandle.getCallingUserId();
6035        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6036        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6037                userId);
6038        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6039                false, false, false, userId);
6040    }
6041
6042    /**
6043     * Returns whether or not instant apps have been disabled remotely.
6044     */
6045    private boolean areWebInstantAppsDisabled() {
6046        return mWebInstantAppsDisabled;
6047    }
6048
6049    private boolean isInstantAppResolutionAllowed(
6050            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6051            boolean skipPackageCheck) {
6052        if (mInstantAppResolverConnection == null) {
6053            return false;
6054        }
6055        if (mInstantAppInstallerActivity == null) {
6056            return false;
6057        }
6058        if (intent.getComponent() != null) {
6059            return false;
6060        }
6061        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6062            return false;
6063        }
6064        if (!skipPackageCheck && intent.getPackage() != null) {
6065            return false;
6066        }
6067        if (!intent.isWebIntent()) {
6068            // for non web intents, we should not resolve externally if an app already exists to
6069            // handle it or if the caller didn't explicitly request it.
6070            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6071                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6072                return false;
6073            }
6074        } else {
6075            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6076                return false;
6077            } else if (areWebInstantAppsDisabled()) {
6078                return false;
6079            }
6080        }
6081        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6082        // Or if there's already an ephemeral app installed that handles the action
6083        synchronized (mPackages) {
6084            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6085            for (int n = 0; n < count; n++) {
6086                final ResolveInfo info = resolvedActivities.get(n);
6087                final String packageName = info.activityInfo.packageName;
6088                final PackageSetting ps = mSettings.mPackages.get(packageName);
6089                if (ps != null) {
6090                    // only check domain verification status if the app is not a browser
6091                    if (!info.handleAllWebDataURI) {
6092                        // Try to get the status from User settings first
6093                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6094                        final int status = (int) (packedStatus >> 32);
6095                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6096                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6097                            if (DEBUG_INSTANT) {
6098                                Slog.v(TAG, "DENY instant app;"
6099                                    + " pkg: " + packageName + ", status: " + status);
6100                            }
6101                            return false;
6102                        }
6103                    }
6104                    if (ps.getInstantApp(userId)) {
6105                        if (DEBUG_INSTANT) {
6106                            Slog.v(TAG, "DENY instant app installed;"
6107                                    + " pkg: " + packageName);
6108                        }
6109                        return false;
6110                    }
6111                }
6112            }
6113        }
6114        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6115        return true;
6116    }
6117
6118    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6119            Intent origIntent, String resolvedType, String callingPackage,
6120            Bundle verificationBundle, int userId) {
6121        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6122                new InstantAppRequest(responseObj, origIntent, resolvedType,
6123                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6124        mHandler.sendMessage(msg);
6125    }
6126
6127    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6128            int flags, List<ResolveInfo> query, int userId) {
6129        if (query != null) {
6130            final int N = query.size();
6131            if (N == 1) {
6132                return query.get(0);
6133            } else if (N > 1) {
6134                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6135                // If there is more than one activity with the same priority,
6136                // then let the user decide between them.
6137                ResolveInfo r0 = query.get(0);
6138                ResolveInfo r1 = query.get(1);
6139                if (DEBUG_INTENT_MATCHING || debug) {
6140                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6141                            + r1.activityInfo.name + "=" + r1.priority);
6142                }
6143                // If the first activity has a higher priority, or a different
6144                // default, then it is always desirable to pick it.
6145                if (r0.priority != r1.priority
6146                        || r0.preferredOrder != r1.preferredOrder
6147                        || r0.isDefault != r1.isDefault) {
6148                    return query.get(0);
6149                }
6150                // If we have saved a preference for a preferred activity for
6151                // this Intent, use that.
6152                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6153                        flags, query, r0.priority, true, false, debug, userId);
6154                if (ri != null) {
6155                    return ri;
6156                }
6157                // If we have an ephemeral app, use it
6158                for (int i = 0; i < N; i++) {
6159                    ri = query.get(i);
6160                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6161                        final String packageName = ri.activityInfo.packageName;
6162                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6163                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6164                        final int status = (int)(packedStatus >> 32);
6165                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6166                            return ri;
6167                        }
6168                    }
6169                }
6170                ri = new ResolveInfo(mResolveInfo);
6171                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6172                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6173                // If all of the options come from the same package, show the application's
6174                // label and icon instead of the generic resolver's.
6175                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6176                // and then throw away the ResolveInfo itself, meaning that the caller loses
6177                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6178                // a fallback for this case; we only set the target package's resources on
6179                // the ResolveInfo, not the ActivityInfo.
6180                final String intentPackage = intent.getPackage();
6181                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6182                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6183                    ri.resolvePackageName = intentPackage;
6184                    if (userNeedsBadging(userId)) {
6185                        ri.noResourceId = true;
6186                    } else {
6187                        ri.icon = appi.icon;
6188                    }
6189                    ri.iconResourceId = appi.icon;
6190                    ri.labelRes = appi.labelRes;
6191                }
6192                ri.activityInfo.applicationInfo = new ApplicationInfo(
6193                        ri.activityInfo.applicationInfo);
6194                if (userId != 0) {
6195                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6196                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6197                }
6198                // Make sure that the resolver is displayable in car mode
6199                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6200                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6201                return ri;
6202            }
6203        }
6204        return null;
6205    }
6206
6207    /**
6208     * Return true if the given list is not empty and all of its contents have
6209     * an activityInfo with the given package name.
6210     */
6211    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6212        if (ArrayUtils.isEmpty(list)) {
6213            return false;
6214        }
6215        for (int i = 0, N = list.size(); i < N; i++) {
6216            final ResolveInfo ri = list.get(i);
6217            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6218            if (ai == null || !packageName.equals(ai.packageName)) {
6219                return false;
6220            }
6221        }
6222        return true;
6223    }
6224
6225    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6226            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6227        final int N = query.size();
6228        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6229                .get(userId);
6230        // Get the list of persistent preferred activities that handle the intent
6231        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6232        List<PersistentPreferredActivity> pprefs = ppir != null
6233                ? ppir.queryIntent(intent, resolvedType,
6234                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6235                        userId)
6236                : null;
6237        if (pprefs != null && pprefs.size() > 0) {
6238            final int M = pprefs.size();
6239            for (int i=0; i<M; i++) {
6240                final PersistentPreferredActivity ppa = pprefs.get(i);
6241                if (DEBUG_PREFERRED || debug) {
6242                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6243                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6244                            + "\n  component=" + ppa.mComponent);
6245                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6246                }
6247                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6248                        flags | MATCH_DISABLED_COMPONENTS, userId);
6249                if (DEBUG_PREFERRED || debug) {
6250                    Slog.v(TAG, "Found persistent preferred activity:");
6251                    if (ai != null) {
6252                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6253                    } else {
6254                        Slog.v(TAG, "  null");
6255                    }
6256                }
6257                if (ai == null) {
6258                    // This previously registered persistent preferred activity
6259                    // component is no longer known. Ignore it and do NOT remove it.
6260                    continue;
6261                }
6262                for (int j=0; j<N; j++) {
6263                    final ResolveInfo ri = query.get(j);
6264                    if (!ri.activityInfo.applicationInfo.packageName
6265                            .equals(ai.applicationInfo.packageName)) {
6266                        continue;
6267                    }
6268                    if (!ri.activityInfo.name.equals(ai.name)) {
6269                        continue;
6270                    }
6271                    //  Found a persistent preference that can handle the intent.
6272                    if (DEBUG_PREFERRED || debug) {
6273                        Slog.v(TAG, "Returning persistent preferred activity: " +
6274                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6275                    }
6276                    return ri;
6277                }
6278            }
6279        }
6280        return null;
6281    }
6282
6283    // TODO: handle preferred activities missing while user has amnesia
6284    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6285            List<ResolveInfo> query, int priority, boolean always,
6286            boolean removeMatches, boolean debug, int userId) {
6287        if (!sUserManager.exists(userId)) return null;
6288        final int callingUid = Binder.getCallingUid();
6289        flags = updateFlagsForResolve(
6290                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6291        intent = updateIntentForResolve(intent);
6292        // writer
6293        synchronized (mPackages) {
6294            // Try to find a matching persistent preferred activity.
6295            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6296                    debug, userId);
6297
6298            // If a persistent preferred activity matched, use it.
6299            if (pri != null) {
6300                return pri;
6301            }
6302
6303            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6304            // Get the list of preferred activities that handle the intent
6305            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6306            List<PreferredActivity> prefs = pir != null
6307                    ? pir.queryIntent(intent, resolvedType,
6308                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6309                            userId)
6310                    : null;
6311            if (prefs != null && prefs.size() > 0) {
6312                boolean changed = false;
6313                try {
6314                    // First figure out how good the original match set is.
6315                    // We will only allow preferred activities that came
6316                    // from the same match quality.
6317                    int match = 0;
6318
6319                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6320
6321                    final int N = query.size();
6322                    for (int j=0; j<N; j++) {
6323                        final ResolveInfo ri = query.get(j);
6324                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6325                                + ": 0x" + Integer.toHexString(match));
6326                        if (ri.match > match) {
6327                            match = ri.match;
6328                        }
6329                    }
6330
6331                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6332                            + Integer.toHexString(match));
6333
6334                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6335                    final int M = prefs.size();
6336                    for (int i=0; i<M; i++) {
6337                        final PreferredActivity pa = prefs.get(i);
6338                        if (DEBUG_PREFERRED || debug) {
6339                            Slog.v(TAG, "Checking PreferredActivity ds="
6340                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6341                                    + "\n  component=" + pa.mPref.mComponent);
6342                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6343                        }
6344                        if (pa.mPref.mMatch != match) {
6345                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6346                                    + Integer.toHexString(pa.mPref.mMatch));
6347                            continue;
6348                        }
6349                        // If it's not an "always" type preferred activity and that's what we're
6350                        // looking for, skip it.
6351                        if (always && !pa.mPref.mAlways) {
6352                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6353                            continue;
6354                        }
6355                        final ActivityInfo ai = getActivityInfo(
6356                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6357                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6358                                userId);
6359                        if (DEBUG_PREFERRED || debug) {
6360                            Slog.v(TAG, "Found preferred activity:");
6361                            if (ai != null) {
6362                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6363                            } else {
6364                                Slog.v(TAG, "  null");
6365                            }
6366                        }
6367                        if (ai == null) {
6368                            // This previously registered preferred activity
6369                            // component is no longer known.  Most likely an update
6370                            // to the app was installed and in the new version this
6371                            // component no longer exists.  Clean it up by removing
6372                            // it from the preferred activities list, and skip it.
6373                            Slog.w(TAG, "Removing dangling preferred activity: "
6374                                    + pa.mPref.mComponent);
6375                            pir.removeFilter(pa);
6376                            changed = true;
6377                            continue;
6378                        }
6379                        for (int j=0; j<N; j++) {
6380                            final ResolveInfo ri = query.get(j);
6381                            if (!ri.activityInfo.applicationInfo.packageName
6382                                    .equals(ai.applicationInfo.packageName)) {
6383                                continue;
6384                            }
6385                            if (!ri.activityInfo.name.equals(ai.name)) {
6386                                continue;
6387                            }
6388
6389                            if (removeMatches) {
6390                                pir.removeFilter(pa);
6391                                changed = true;
6392                                if (DEBUG_PREFERRED) {
6393                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6394                                }
6395                                break;
6396                            }
6397
6398                            // Okay we found a previously set preferred or last chosen app.
6399                            // If the result set is different from when this
6400                            // was created, and is not a subset of the preferred set, we need to
6401                            // clear it and re-ask the user their preference, if we're looking for
6402                            // an "always" type entry.
6403                            if (always && !pa.mPref.sameSet(query)) {
6404                                if (pa.mPref.isSuperset(query)) {
6405                                    // some components of the set are no longer present in
6406                                    // the query, but the preferred activity can still be reused
6407                                    if (DEBUG_PREFERRED) {
6408                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6409                                                + " still valid as only non-preferred components"
6410                                                + " were removed for " + intent + " type "
6411                                                + resolvedType);
6412                                    }
6413                                    // remove obsolete components and re-add the up-to-date filter
6414                                    PreferredActivity freshPa = new PreferredActivity(pa,
6415                                            pa.mPref.mMatch,
6416                                            pa.mPref.discardObsoleteComponents(query),
6417                                            pa.mPref.mComponent,
6418                                            pa.mPref.mAlways);
6419                                    pir.removeFilter(pa);
6420                                    pir.addFilter(freshPa);
6421                                    changed = true;
6422                                } else {
6423                                    Slog.i(TAG,
6424                                            "Result set changed, dropping preferred activity for "
6425                                                    + intent + " type " + resolvedType);
6426                                    if (DEBUG_PREFERRED) {
6427                                        Slog.v(TAG, "Removing preferred activity since set changed "
6428                                                + pa.mPref.mComponent);
6429                                    }
6430                                    pir.removeFilter(pa);
6431                                    // Re-add the filter as a "last chosen" entry (!always)
6432                                    PreferredActivity lastChosen = new PreferredActivity(
6433                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6434                                    pir.addFilter(lastChosen);
6435                                    changed = true;
6436                                    return null;
6437                                }
6438                            }
6439
6440                            // Yay! Either the set matched or we're looking for the last chosen
6441                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6442                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6443                            return ri;
6444                        }
6445                    }
6446                } finally {
6447                    if (changed) {
6448                        if (DEBUG_PREFERRED) {
6449                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6450                        }
6451                        scheduleWritePackageRestrictionsLocked(userId);
6452                    }
6453                }
6454            }
6455        }
6456        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6457        return null;
6458    }
6459
6460    /*
6461     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6462     */
6463    @Override
6464    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6465            int targetUserId) {
6466        mContext.enforceCallingOrSelfPermission(
6467                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6468        List<CrossProfileIntentFilter> matches =
6469                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6470        if (matches != null) {
6471            int size = matches.size();
6472            for (int i = 0; i < size; i++) {
6473                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6474            }
6475        }
6476        if (intent.hasWebURI()) {
6477            // cross-profile app linking works only towards the parent.
6478            final int callingUid = Binder.getCallingUid();
6479            final UserInfo parent = getProfileParent(sourceUserId);
6480            synchronized(mPackages) {
6481                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6482                        false /*includeInstantApps*/);
6483                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6484                        intent, resolvedType, flags, sourceUserId, parent.id);
6485                return xpDomainInfo != null;
6486            }
6487        }
6488        return false;
6489    }
6490
6491    private UserInfo getProfileParent(int userId) {
6492        final long identity = Binder.clearCallingIdentity();
6493        try {
6494            return sUserManager.getProfileParent(userId);
6495        } finally {
6496            Binder.restoreCallingIdentity(identity);
6497        }
6498    }
6499
6500    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6501            String resolvedType, int userId) {
6502        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6503        if (resolver != null) {
6504            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6505        }
6506        return null;
6507    }
6508
6509    @Override
6510    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6511            String resolvedType, int flags, int userId) {
6512        try {
6513            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6514
6515            return new ParceledListSlice<>(
6516                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6517        } finally {
6518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6519        }
6520    }
6521
6522    /**
6523     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6524     * instant, returns {@code null}.
6525     */
6526    private String getInstantAppPackageName(int callingUid) {
6527        synchronized (mPackages) {
6528            // If the caller is an isolated app use the owner's uid for the lookup.
6529            if (Process.isIsolated(callingUid)) {
6530                callingUid = mIsolatedOwners.get(callingUid);
6531            }
6532            final int appId = UserHandle.getAppId(callingUid);
6533            final Object obj = mSettings.getUserIdLPr(appId);
6534            if (obj instanceof PackageSetting) {
6535                final PackageSetting ps = (PackageSetting) obj;
6536                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6537                return isInstantApp ? ps.pkg.packageName : null;
6538            }
6539        }
6540        return null;
6541    }
6542
6543    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6544            String resolvedType, int flags, int userId) {
6545        return queryIntentActivitiesInternal(
6546                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6547                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6548    }
6549
6550    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6551            String resolvedType, int flags, int filterCallingUid, int userId,
6552            boolean resolveForStart, boolean allowDynamicSplits) {
6553        if (!sUserManager.exists(userId)) return Collections.emptyList();
6554        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6555        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6556                false /* requireFullPermission */, false /* checkShell */,
6557                "query intent activities");
6558        final String pkgName = intent.getPackage();
6559        ComponentName comp = intent.getComponent();
6560        if (comp == null) {
6561            if (intent.getSelector() != null) {
6562                intent = intent.getSelector();
6563                comp = intent.getComponent();
6564            }
6565        }
6566
6567        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6568                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6569        if (comp != null) {
6570            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6571            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6572            if (ai != null) {
6573                // When specifying an explicit component, we prevent the activity from being
6574                // used when either 1) the calling package is normal and the activity is within
6575                // an ephemeral application or 2) the calling package is ephemeral and the
6576                // activity is not visible to ephemeral applications.
6577                final boolean matchInstantApp =
6578                        (flags & PackageManager.MATCH_INSTANT) != 0;
6579                final boolean matchVisibleToInstantAppOnly =
6580                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6581                final boolean matchExplicitlyVisibleOnly =
6582                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6583                final boolean isCallerInstantApp =
6584                        instantAppPkgName != null;
6585                final boolean isTargetSameInstantApp =
6586                        comp.getPackageName().equals(instantAppPkgName);
6587                final boolean isTargetInstantApp =
6588                        (ai.applicationInfo.privateFlags
6589                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6590                final boolean isTargetVisibleToInstantApp =
6591                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6592                final boolean isTargetExplicitlyVisibleToInstantApp =
6593                        isTargetVisibleToInstantApp
6594                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6595                final boolean isTargetHiddenFromInstantApp =
6596                        !isTargetVisibleToInstantApp
6597                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6598                final boolean blockResolution =
6599                        !isTargetSameInstantApp
6600                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6601                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6602                                        && isTargetHiddenFromInstantApp));
6603                if (!blockResolution) {
6604                    final ResolveInfo ri = new ResolveInfo();
6605                    ri.activityInfo = ai;
6606                    list.add(ri);
6607                }
6608            }
6609            return applyPostResolutionFilter(
6610                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6611        }
6612
6613        // reader
6614        boolean sortResult = false;
6615        boolean addInstant = false;
6616        List<ResolveInfo> result;
6617        synchronized (mPackages) {
6618            if (pkgName == null) {
6619                List<CrossProfileIntentFilter> matchingFilters =
6620                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6621                // Check for results that need to skip the current profile.
6622                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6623                        resolvedType, flags, userId);
6624                if (xpResolveInfo != null) {
6625                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6626                    xpResult.add(xpResolveInfo);
6627                    return applyPostResolutionFilter(
6628                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6629                            allowDynamicSplits, filterCallingUid, userId, intent);
6630                }
6631
6632                // Check for results in the current profile.
6633                result = filterIfNotSystemUser(mActivities.queryIntent(
6634                        intent, resolvedType, flags, userId), userId);
6635                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6636                        false /*skipPackageCheck*/);
6637                // Check for cross profile results.
6638                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6639                xpResolveInfo = queryCrossProfileIntents(
6640                        matchingFilters, intent, resolvedType, flags, userId,
6641                        hasNonNegativePriorityResult);
6642                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6643                    boolean isVisibleToUser = filterIfNotSystemUser(
6644                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6645                    if (isVisibleToUser) {
6646                        result.add(xpResolveInfo);
6647                        sortResult = true;
6648                    }
6649                }
6650                if (intent.hasWebURI()) {
6651                    CrossProfileDomainInfo xpDomainInfo = null;
6652                    final UserInfo parent = getProfileParent(userId);
6653                    if (parent != null) {
6654                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6655                                flags, userId, parent.id);
6656                    }
6657                    if (xpDomainInfo != null) {
6658                        if (xpResolveInfo != null) {
6659                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6660                            // in the result.
6661                            result.remove(xpResolveInfo);
6662                        }
6663                        if (result.size() == 0 && !addInstant) {
6664                            // No result in current profile, but found candidate in parent user.
6665                            // And we are not going to add emphemeral app, so we can return the
6666                            // result straight away.
6667                            result.add(xpDomainInfo.resolveInfo);
6668                            return applyPostResolutionFilter(result, instantAppPkgName,
6669                                    allowDynamicSplits, filterCallingUid, userId, intent);
6670                        }
6671                    } else if (result.size() <= 1 && !addInstant) {
6672                        // No result in parent user and <= 1 result in current profile, and we
6673                        // are not going to add emphemeral app, so we can return the result without
6674                        // further processing.
6675                        return applyPostResolutionFilter(result, instantAppPkgName,
6676                                allowDynamicSplits, filterCallingUid, userId, intent);
6677                    }
6678                    // We have more than one candidate (combining results from current and parent
6679                    // profile), so we need filtering and sorting.
6680                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6681                            intent, flags, result, xpDomainInfo, userId);
6682                    sortResult = true;
6683                }
6684            } else {
6685                final PackageParser.Package pkg = mPackages.get(pkgName);
6686                result = null;
6687                if (pkg != null) {
6688                    result = filterIfNotSystemUser(
6689                            mActivities.queryIntentForPackage(
6690                                    intent, resolvedType, flags, pkg.activities, userId),
6691                            userId);
6692                }
6693                if (result == null || result.size() == 0) {
6694                    // the caller wants to resolve for a particular package; however, there
6695                    // were no installed results, so, try to find an ephemeral result
6696                    addInstant = isInstantAppResolutionAllowed(
6697                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6698                    if (result == null) {
6699                        result = new ArrayList<>();
6700                    }
6701                }
6702            }
6703        }
6704        if (addInstant) {
6705            result = maybeAddInstantAppInstaller(
6706                    result, intent, resolvedType, flags, userId, resolveForStart);
6707        }
6708        if (sortResult) {
6709            Collections.sort(result, mResolvePrioritySorter);
6710        }
6711        return applyPostResolutionFilter(
6712                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6713    }
6714
6715    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6716            String resolvedType, int flags, int userId, boolean resolveForStart) {
6717        // first, check to see if we've got an instant app already installed
6718        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6719        ResolveInfo localInstantApp = null;
6720        boolean blockResolution = false;
6721        if (!alreadyResolvedLocally) {
6722            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6723                    flags
6724                        | PackageManager.GET_RESOLVED_FILTER
6725                        | PackageManager.MATCH_INSTANT
6726                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6727                    userId);
6728            for (int i = instantApps.size() - 1; i >= 0; --i) {
6729                final ResolveInfo info = instantApps.get(i);
6730                final String packageName = info.activityInfo.packageName;
6731                final PackageSetting ps = mSettings.mPackages.get(packageName);
6732                if (ps.getInstantApp(userId)) {
6733                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6734                    final int status = (int)(packedStatus >> 32);
6735                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6736                        // there's a local instant application installed, but, the user has
6737                        // chosen to never use it; skip resolution and don't acknowledge
6738                        // an instant application is even available
6739                        if (DEBUG_INSTANT) {
6740                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6741                        }
6742                        blockResolution = true;
6743                        break;
6744                    } else {
6745                        // we have a locally installed instant application; skip resolution
6746                        // but acknowledge there's an instant application available
6747                        if (DEBUG_INSTANT) {
6748                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6749                        }
6750                        localInstantApp = info;
6751                        break;
6752                    }
6753                }
6754            }
6755        }
6756        // no app installed, let's see if one's available
6757        AuxiliaryResolveInfo auxiliaryResponse = null;
6758        if (!blockResolution) {
6759            if (localInstantApp == null) {
6760                // we don't have an instant app locally, resolve externally
6761                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6762                final InstantAppRequest requestObject = new InstantAppRequest(
6763                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6764                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6765                        resolveForStart);
6766                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6767                        mInstantAppResolverConnection, requestObject);
6768                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6769            } else {
6770                // we have an instant application locally, but, we can't admit that since
6771                // callers shouldn't be able to determine prior browsing. create a dummy
6772                // auxiliary response so the downstream code behaves as if there's an
6773                // instant application available externally. when it comes time to start
6774                // the instant application, we'll do the right thing.
6775                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6776                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6777                                        ai.packageName, ai.longVersionCode, null /* splitName */);
6778            }
6779        }
6780        if (intent.isWebIntent() && auxiliaryResponse == null) {
6781            return result;
6782        }
6783        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6784        if (ps == null
6785                || ps.getUserState().get(userId) == null
6786                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6787            return result;
6788        }
6789        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6790        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6791                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6792        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6793                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6794        // add a non-generic filter
6795        ephemeralInstaller.filter = new IntentFilter();
6796        if (intent.getAction() != null) {
6797            ephemeralInstaller.filter.addAction(intent.getAction());
6798        }
6799        if (intent.getData() != null && intent.getData().getPath() != null) {
6800            ephemeralInstaller.filter.addDataPath(
6801                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6802        }
6803        ephemeralInstaller.isInstantAppAvailable = true;
6804        // make sure this resolver is the default
6805        ephemeralInstaller.isDefault = true;
6806        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6807        if (DEBUG_INSTANT) {
6808            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6809        }
6810
6811        result.add(ephemeralInstaller);
6812        return result;
6813    }
6814
6815    private static class CrossProfileDomainInfo {
6816        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6817        ResolveInfo resolveInfo;
6818        /* Best domain verification status of the activities found in the other profile */
6819        int bestDomainVerificationStatus;
6820    }
6821
6822    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6823            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6824        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6825                sourceUserId)) {
6826            return null;
6827        }
6828        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6829                resolvedType, flags, parentUserId);
6830
6831        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6832            return null;
6833        }
6834        CrossProfileDomainInfo result = null;
6835        int size = resultTargetUser.size();
6836        for (int i = 0; i < size; i++) {
6837            ResolveInfo riTargetUser = resultTargetUser.get(i);
6838            // Intent filter verification is only for filters that specify a host. So don't return
6839            // those that handle all web uris.
6840            if (riTargetUser.handleAllWebDataURI) {
6841                continue;
6842            }
6843            String packageName = riTargetUser.activityInfo.packageName;
6844            PackageSetting ps = mSettings.mPackages.get(packageName);
6845            if (ps == null) {
6846                continue;
6847            }
6848            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6849            int status = (int)(verificationState >> 32);
6850            if (result == null) {
6851                result = new CrossProfileDomainInfo();
6852                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6853                        sourceUserId, parentUserId);
6854                result.bestDomainVerificationStatus = status;
6855            } else {
6856                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6857                        result.bestDomainVerificationStatus);
6858            }
6859        }
6860        // Don't consider matches with status NEVER across profiles.
6861        if (result != null && result.bestDomainVerificationStatus
6862                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6863            return null;
6864        }
6865        return result;
6866    }
6867
6868    /**
6869     * Verification statuses are ordered from the worse to the best, except for
6870     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6871     */
6872    private int bestDomainVerificationStatus(int status1, int status2) {
6873        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6874            return status2;
6875        }
6876        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6877            return status1;
6878        }
6879        return (int) MathUtils.max(status1, status2);
6880    }
6881
6882    private boolean isUserEnabled(int userId) {
6883        long callingId = Binder.clearCallingIdentity();
6884        try {
6885            UserInfo userInfo = sUserManager.getUserInfo(userId);
6886            return userInfo != null && userInfo.isEnabled();
6887        } finally {
6888            Binder.restoreCallingIdentity(callingId);
6889        }
6890    }
6891
6892    /**
6893     * Filter out activities with systemUserOnly flag set, when current user is not System.
6894     *
6895     * @return filtered list
6896     */
6897    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6898        if (userId == UserHandle.USER_SYSTEM) {
6899            return resolveInfos;
6900        }
6901        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6902            ResolveInfo info = resolveInfos.get(i);
6903            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6904                resolveInfos.remove(i);
6905            }
6906        }
6907        return resolveInfos;
6908    }
6909
6910    /**
6911     * Filters out ephemeral activities.
6912     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6913     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6914     *
6915     * @param resolveInfos The pre-filtered list of resolved activities
6916     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6917     *          is performed.
6918     * @param intent
6919     * @return A filtered list of resolved activities.
6920     */
6921    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6922            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6923            Intent intent) {
6924        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6925        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6926            final ResolveInfo info = resolveInfos.get(i);
6927            // remove locally resolved instant app web results when disabled
6928            if (info.isInstantAppAvailable && blockInstant) {
6929                resolveInfos.remove(i);
6930                continue;
6931            }
6932            // allow activities that are defined in the provided package
6933            if (allowDynamicSplits
6934                    && info.activityInfo != null
6935                    && info.activityInfo.splitName != null
6936                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6937                            info.activityInfo.splitName)) {
6938                if (mInstantAppInstallerActivity == null) {
6939                    if (DEBUG_INSTALL) {
6940                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6941                    }
6942                    resolveInfos.remove(i);
6943                    continue;
6944                }
6945                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6946                    resolveInfos.remove(i);
6947                    continue;
6948                }
6949                // requested activity is defined in a split that hasn't been installed yet.
6950                // add the installer to the resolve list
6951                if (DEBUG_INSTALL) {
6952                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6953                }
6954                final ResolveInfo installerInfo = new ResolveInfo(
6955                        mInstantAppInstallerInfo);
6956                final ComponentName installFailureActivity = findInstallFailureActivity(
6957                        info.activityInfo.packageName,  filterCallingUid, userId);
6958                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6959                        installFailureActivity,
6960                        info.activityInfo.packageName,
6961                        info.activityInfo.applicationInfo.longVersionCode,
6962                        info.activityInfo.splitName);
6963                // add a non-generic filter
6964                installerInfo.filter = new IntentFilter();
6965
6966                // This resolve info may appear in the chooser UI, so let us make it
6967                // look as the one it replaces as far as the user is concerned which
6968                // requires loading the correct label and icon for the resolve info.
6969                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6970                installerInfo.labelRes = info.resolveLabelResId();
6971                installerInfo.icon = info.resolveIconResId();
6972                installerInfo.isInstantAppAvailable = true;
6973                resolveInfos.set(i, installerInfo);
6974                continue;
6975            }
6976            // caller is a full app, don't need to apply any other filtering
6977            if (ephemeralPkgName == null) {
6978                continue;
6979            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6980                // caller is same app; don't need to apply any other filtering
6981                continue;
6982            }
6983            // allow activities that have been explicitly exposed to ephemeral apps
6984            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6985            if (!isEphemeralApp
6986                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6987                continue;
6988            }
6989            resolveInfos.remove(i);
6990        }
6991        return resolveInfos;
6992    }
6993
6994    /**
6995     * Returns the activity component that can handle install failures.
6996     * <p>By default, the instant application installer handles failures. However, an
6997     * application may want to handle failures on its own. Applications do this by
6998     * creating an activity with an intent filter that handles the action
6999     * {@link Intent#ACTION_INSTALL_FAILURE}.
7000     */
7001    private @Nullable ComponentName findInstallFailureActivity(
7002            String packageName, int filterCallingUid, int userId) {
7003        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7004        failureActivityIntent.setPackage(packageName);
7005        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7006        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7007                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7008                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7009        final int NR = result.size();
7010        if (NR > 0) {
7011            for (int i = 0; i < NR; i++) {
7012                final ResolveInfo info = result.get(i);
7013                if (info.activityInfo.splitName != null) {
7014                    continue;
7015                }
7016                return new ComponentName(packageName, info.activityInfo.name);
7017            }
7018        }
7019        return null;
7020    }
7021
7022    /**
7023     * @param resolveInfos list of resolve infos in descending priority order
7024     * @return if the list contains a resolve info with non-negative priority
7025     */
7026    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7027        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7028    }
7029
7030    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7031            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7032            int userId) {
7033        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7034
7035        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7036            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7037                    candidates.size());
7038        }
7039
7040        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7041        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7042        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7043        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7044        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7045        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7046
7047        synchronized (mPackages) {
7048            final int count = candidates.size();
7049            // First, try to use linked apps. Partition the candidates into four lists:
7050            // one for the final results, one for the "do not use ever", one for "undefined status"
7051            // and finally one for "browser app type".
7052            for (int n=0; n<count; n++) {
7053                ResolveInfo info = candidates.get(n);
7054                String packageName = info.activityInfo.packageName;
7055                PackageSetting ps = mSettings.mPackages.get(packageName);
7056                if (ps != null) {
7057                    // Add to the special match all list (Browser use case)
7058                    if (info.handleAllWebDataURI) {
7059                        matchAllList.add(info);
7060                        continue;
7061                    }
7062                    // Try to get the status from User settings first
7063                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7064                    int status = (int)(packedStatus >> 32);
7065                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7066                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7067                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7068                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7069                                    + " : linkgen=" + linkGeneration);
7070                        }
7071                        // Use link-enabled generation as preferredOrder, i.e.
7072                        // prefer newly-enabled over earlier-enabled.
7073                        info.preferredOrder = linkGeneration;
7074                        alwaysList.add(info);
7075                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7076                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7077                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7078                        }
7079                        neverList.add(info);
7080                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7081                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7082                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7083                        }
7084                        alwaysAskList.add(info);
7085                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7086                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7087                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7088                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7089                        }
7090                        undefinedList.add(info);
7091                    }
7092                }
7093            }
7094
7095            // We'll want to include browser possibilities in a few cases
7096            boolean includeBrowser = false;
7097
7098            // First try to add the "always" resolution(s) for the current user, if any
7099            if (alwaysList.size() > 0) {
7100                result.addAll(alwaysList);
7101            } else {
7102                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7103                result.addAll(undefinedList);
7104                // Maybe add one for the other profile.
7105                if (xpDomainInfo != null && (
7106                        xpDomainInfo.bestDomainVerificationStatus
7107                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7108                    result.add(xpDomainInfo.resolveInfo);
7109                }
7110                includeBrowser = true;
7111            }
7112
7113            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7114            // If there were 'always' entries their preferred order has been set, so we also
7115            // back that off to make the alternatives equivalent
7116            if (alwaysAskList.size() > 0) {
7117                for (ResolveInfo i : result) {
7118                    i.preferredOrder = 0;
7119                }
7120                result.addAll(alwaysAskList);
7121                includeBrowser = true;
7122            }
7123
7124            if (includeBrowser) {
7125                // Also add browsers (all of them or only the default one)
7126                if (DEBUG_DOMAIN_VERIFICATION) {
7127                    Slog.v(TAG, "   ...including browsers in candidate set");
7128                }
7129                if ((matchFlags & MATCH_ALL) != 0) {
7130                    result.addAll(matchAllList);
7131                } else {
7132                    // Browser/generic handling case.  If there's a default browser, go straight
7133                    // to that (but only if there is no other higher-priority match).
7134                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7135                    int maxMatchPrio = 0;
7136                    ResolveInfo defaultBrowserMatch = null;
7137                    final int numCandidates = matchAllList.size();
7138                    for (int n = 0; n < numCandidates; n++) {
7139                        ResolveInfo info = matchAllList.get(n);
7140                        // track the highest overall match priority...
7141                        if (info.priority > maxMatchPrio) {
7142                            maxMatchPrio = info.priority;
7143                        }
7144                        // ...and the highest-priority default browser match
7145                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7146                            if (defaultBrowserMatch == null
7147                                    || (defaultBrowserMatch.priority < info.priority)) {
7148                                if (debug) {
7149                                    Slog.v(TAG, "Considering default browser match " + info);
7150                                }
7151                                defaultBrowserMatch = info;
7152                            }
7153                        }
7154                    }
7155                    if (defaultBrowserMatch != null
7156                            && defaultBrowserMatch.priority >= maxMatchPrio
7157                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7158                    {
7159                        if (debug) {
7160                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7161                        }
7162                        result.add(defaultBrowserMatch);
7163                    } else {
7164                        result.addAll(matchAllList);
7165                    }
7166                }
7167
7168                // If there is nothing selected, add all candidates and remove the ones that the user
7169                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7170                if (result.size() == 0) {
7171                    result.addAll(candidates);
7172                    result.removeAll(neverList);
7173                }
7174            }
7175        }
7176        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7177            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7178                    result.size());
7179            for (ResolveInfo info : result) {
7180                Slog.v(TAG, "  + " + info.activityInfo);
7181            }
7182        }
7183        return result;
7184    }
7185
7186    // Returns a packed value as a long:
7187    //
7188    // high 'int'-sized word: link status: undefined/ask/never/always.
7189    // low 'int'-sized word: relative priority among 'always' results.
7190    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7191        long result = ps.getDomainVerificationStatusForUser(userId);
7192        // if none available, get the master status
7193        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7194            if (ps.getIntentFilterVerificationInfo() != null) {
7195                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7196            }
7197        }
7198        return result;
7199    }
7200
7201    private ResolveInfo querySkipCurrentProfileIntents(
7202            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7203            int flags, int sourceUserId) {
7204        if (matchingFilters != null) {
7205            int size = matchingFilters.size();
7206            for (int i = 0; i < size; i ++) {
7207                CrossProfileIntentFilter filter = matchingFilters.get(i);
7208                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7209                    // Checking if there are activities in the target user that can handle the
7210                    // intent.
7211                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7212                            resolvedType, flags, sourceUserId);
7213                    if (resolveInfo != null) {
7214                        return resolveInfo;
7215                    }
7216                }
7217            }
7218        }
7219        return null;
7220    }
7221
7222    // Return matching ResolveInfo in target user if any.
7223    private ResolveInfo queryCrossProfileIntents(
7224            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7225            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7226        if (matchingFilters != null) {
7227            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7228            // match the same intent. For performance reasons, it is better not to
7229            // run queryIntent twice for the same userId
7230            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7231            int size = matchingFilters.size();
7232            for (int i = 0; i < size; i++) {
7233                CrossProfileIntentFilter filter = matchingFilters.get(i);
7234                int targetUserId = filter.getTargetUserId();
7235                boolean skipCurrentProfile =
7236                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7237                boolean skipCurrentProfileIfNoMatchFound =
7238                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7239                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7240                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7241                    // Checking if there are activities in the target user that can handle the
7242                    // intent.
7243                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7244                            resolvedType, flags, sourceUserId);
7245                    if (resolveInfo != null) return resolveInfo;
7246                    alreadyTriedUserIds.put(targetUserId, true);
7247                }
7248            }
7249        }
7250        return null;
7251    }
7252
7253    /**
7254     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7255     * will forward the intent to the filter's target user.
7256     * Otherwise, returns null.
7257     */
7258    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7259            String resolvedType, int flags, int sourceUserId) {
7260        int targetUserId = filter.getTargetUserId();
7261        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7262                resolvedType, flags, targetUserId);
7263        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7264            // If all the matches in the target profile are suspended, return null.
7265            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7266                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7267                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7268                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7269                            targetUserId);
7270                }
7271            }
7272        }
7273        return null;
7274    }
7275
7276    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7277            int sourceUserId, int targetUserId) {
7278        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7279        long ident = Binder.clearCallingIdentity();
7280        boolean targetIsProfile;
7281        try {
7282            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7283        } finally {
7284            Binder.restoreCallingIdentity(ident);
7285        }
7286        String className;
7287        if (targetIsProfile) {
7288            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7289        } else {
7290            className = FORWARD_INTENT_TO_PARENT;
7291        }
7292        ComponentName forwardingActivityComponentName = new ComponentName(
7293                mAndroidApplication.packageName, className);
7294        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7295                sourceUserId);
7296        if (!targetIsProfile) {
7297            forwardingActivityInfo.showUserIcon = targetUserId;
7298            forwardingResolveInfo.noResourceId = true;
7299        }
7300        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7301        forwardingResolveInfo.priority = 0;
7302        forwardingResolveInfo.preferredOrder = 0;
7303        forwardingResolveInfo.match = 0;
7304        forwardingResolveInfo.isDefault = true;
7305        forwardingResolveInfo.filter = filter;
7306        forwardingResolveInfo.targetUserId = targetUserId;
7307        return forwardingResolveInfo;
7308    }
7309
7310    @Override
7311    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7312            Intent[] specifics, String[] specificTypes, Intent intent,
7313            String resolvedType, int flags, int userId) {
7314        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7315                specificTypes, intent, resolvedType, flags, userId));
7316    }
7317
7318    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7319            Intent[] specifics, String[] specificTypes, Intent intent,
7320            String resolvedType, int flags, int userId) {
7321        if (!sUserManager.exists(userId)) return Collections.emptyList();
7322        final int callingUid = Binder.getCallingUid();
7323        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7324                false /*includeInstantApps*/);
7325        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7326                false /*requireFullPermission*/, false /*checkShell*/,
7327                "query intent activity options");
7328        final String resultsAction = intent.getAction();
7329
7330        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7331                | PackageManager.GET_RESOLVED_FILTER, userId);
7332
7333        if (DEBUG_INTENT_MATCHING) {
7334            Log.v(TAG, "Query " + intent + ": " + results);
7335        }
7336
7337        int specificsPos = 0;
7338        int N;
7339
7340        // todo: note that the algorithm used here is O(N^2).  This
7341        // isn't a problem in our current environment, but if we start running
7342        // into situations where we have more than 5 or 10 matches then this
7343        // should probably be changed to something smarter...
7344
7345        // First we go through and resolve each of the specific items
7346        // that were supplied, taking care of removing any corresponding
7347        // duplicate items in the generic resolve list.
7348        if (specifics != null) {
7349            for (int i=0; i<specifics.length; i++) {
7350                final Intent sintent = specifics[i];
7351                if (sintent == null) {
7352                    continue;
7353                }
7354
7355                if (DEBUG_INTENT_MATCHING) {
7356                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7357                }
7358
7359                String action = sintent.getAction();
7360                if (resultsAction != null && resultsAction.equals(action)) {
7361                    // If this action was explicitly requested, then don't
7362                    // remove things that have it.
7363                    action = null;
7364                }
7365
7366                ResolveInfo ri = null;
7367                ActivityInfo ai = null;
7368
7369                ComponentName comp = sintent.getComponent();
7370                if (comp == null) {
7371                    ri = resolveIntent(
7372                        sintent,
7373                        specificTypes != null ? specificTypes[i] : null,
7374                            flags, userId);
7375                    if (ri == null) {
7376                        continue;
7377                    }
7378                    if (ri == mResolveInfo) {
7379                        // ACK!  Must do something better with this.
7380                    }
7381                    ai = ri.activityInfo;
7382                    comp = new ComponentName(ai.applicationInfo.packageName,
7383                            ai.name);
7384                } else {
7385                    ai = getActivityInfo(comp, flags, userId);
7386                    if (ai == null) {
7387                        continue;
7388                    }
7389                }
7390
7391                // Look for any generic query activities that are duplicates
7392                // of this specific one, and remove them from the results.
7393                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7394                N = results.size();
7395                int j;
7396                for (j=specificsPos; j<N; j++) {
7397                    ResolveInfo sri = results.get(j);
7398                    if ((sri.activityInfo.name.equals(comp.getClassName())
7399                            && sri.activityInfo.applicationInfo.packageName.equals(
7400                                    comp.getPackageName()))
7401                        || (action != null && sri.filter.matchAction(action))) {
7402                        results.remove(j);
7403                        if (DEBUG_INTENT_MATCHING) Log.v(
7404                            TAG, "Removing duplicate item from " + j
7405                            + " due to specific " + specificsPos);
7406                        if (ri == null) {
7407                            ri = sri;
7408                        }
7409                        j--;
7410                        N--;
7411                    }
7412                }
7413
7414                // Add this specific item to its proper place.
7415                if (ri == null) {
7416                    ri = new ResolveInfo();
7417                    ri.activityInfo = ai;
7418                }
7419                results.add(specificsPos, ri);
7420                ri.specificIndex = i;
7421                specificsPos++;
7422            }
7423        }
7424
7425        // Now we go through the remaining generic results and remove any
7426        // duplicate actions that are found here.
7427        N = results.size();
7428        for (int i=specificsPos; i<N-1; i++) {
7429            final ResolveInfo rii = results.get(i);
7430            if (rii.filter == null) {
7431                continue;
7432            }
7433
7434            // Iterate over all of the actions of this result's intent
7435            // filter...  typically this should be just one.
7436            final Iterator<String> it = rii.filter.actionsIterator();
7437            if (it == null) {
7438                continue;
7439            }
7440            while (it.hasNext()) {
7441                final String action = it.next();
7442                if (resultsAction != null && resultsAction.equals(action)) {
7443                    // If this action was explicitly requested, then don't
7444                    // remove things that have it.
7445                    continue;
7446                }
7447                for (int j=i+1; j<N; j++) {
7448                    final ResolveInfo rij = results.get(j);
7449                    if (rij.filter != null && rij.filter.hasAction(action)) {
7450                        results.remove(j);
7451                        if (DEBUG_INTENT_MATCHING) Log.v(
7452                            TAG, "Removing duplicate item from " + j
7453                            + " due to action " + action + " at " + i);
7454                        j--;
7455                        N--;
7456                    }
7457                }
7458            }
7459
7460            // If the caller didn't request filter information, drop it now
7461            // so we don't have to marshall/unmarshall it.
7462            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7463                rii.filter = null;
7464            }
7465        }
7466
7467        // Filter out the caller activity if so requested.
7468        if (caller != null) {
7469            N = results.size();
7470            for (int i=0; i<N; i++) {
7471                ActivityInfo ainfo = results.get(i).activityInfo;
7472                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7473                        && caller.getClassName().equals(ainfo.name)) {
7474                    results.remove(i);
7475                    break;
7476                }
7477            }
7478        }
7479
7480        // If the caller didn't request filter information,
7481        // drop them now so we don't have to
7482        // marshall/unmarshall it.
7483        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7484            N = results.size();
7485            for (int i=0; i<N; i++) {
7486                results.get(i).filter = null;
7487            }
7488        }
7489
7490        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7491        return results;
7492    }
7493
7494    @Override
7495    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7496            String resolvedType, int flags, int userId) {
7497        return new ParceledListSlice<>(
7498                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7499                        false /*allowDynamicSplits*/));
7500    }
7501
7502    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7503            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7504        if (!sUserManager.exists(userId)) return Collections.emptyList();
7505        final int callingUid = Binder.getCallingUid();
7506        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7507                false /*requireFullPermission*/, false /*checkShell*/,
7508                "query intent receivers");
7509        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7510        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7511                false /*includeInstantApps*/);
7512        ComponentName comp = intent.getComponent();
7513        if (comp == null) {
7514            if (intent.getSelector() != null) {
7515                intent = intent.getSelector();
7516                comp = intent.getComponent();
7517            }
7518        }
7519        if (comp != null) {
7520            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7521            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7522            if (ai != null) {
7523                // When specifying an explicit component, we prevent the activity from being
7524                // used when either 1) the calling package is normal and the activity is within
7525                // an instant application or 2) the calling package is ephemeral and the
7526                // activity is not visible to instant applications.
7527                final boolean matchInstantApp =
7528                        (flags & PackageManager.MATCH_INSTANT) != 0;
7529                final boolean matchVisibleToInstantAppOnly =
7530                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7531                final boolean matchExplicitlyVisibleOnly =
7532                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7533                final boolean isCallerInstantApp =
7534                        instantAppPkgName != null;
7535                final boolean isTargetSameInstantApp =
7536                        comp.getPackageName().equals(instantAppPkgName);
7537                final boolean isTargetInstantApp =
7538                        (ai.applicationInfo.privateFlags
7539                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7540                final boolean isTargetVisibleToInstantApp =
7541                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7542                final boolean isTargetExplicitlyVisibleToInstantApp =
7543                        isTargetVisibleToInstantApp
7544                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7545                final boolean isTargetHiddenFromInstantApp =
7546                        !isTargetVisibleToInstantApp
7547                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7548                final boolean blockResolution =
7549                        !isTargetSameInstantApp
7550                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7551                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7552                                        && isTargetHiddenFromInstantApp));
7553                if (!blockResolution) {
7554                    ResolveInfo ri = new ResolveInfo();
7555                    ri.activityInfo = ai;
7556                    list.add(ri);
7557                }
7558            }
7559            return applyPostResolutionFilter(
7560                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7561        }
7562
7563        // reader
7564        synchronized (mPackages) {
7565            String pkgName = intent.getPackage();
7566            if (pkgName == null) {
7567                final List<ResolveInfo> result =
7568                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7569                return applyPostResolutionFilter(
7570                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7571            }
7572            final PackageParser.Package pkg = mPackages.get(pkgName);
7573            if (pkg != null) {
7574                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7575                        intent, resolvedType, flags, pkg.receivers, userId);
7576                return applyPostResolutionFilter(
7577                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7578            }
7579            return Collections.emptyList();
7580        }
7581    }
7582
7583    @Override
7584    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7585        final int callingUid = Binder.getCallingUid();
7586        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7587    }
7588
7589    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7590            int userId, int callingUid) {
7591        if (!sUserManager.exists(userId)) return null;
7592        flags = updateFlagsForResolve(
7593                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7594        List<ResolveInfo> query = queryIntentServicesInternal(
7595                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7596        if (query != null) {
7597            if (query.size() >= 1) {
7598                // If there is more than one service with the same priority,
7599                // just arbitrarily pick the first one.
7600                return query.get(0);
7601            }
7602        }
7603        return null;
7604    }
7605
7606    @Override
7607    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7608            String resolvedType, int flags, int userId) {
7609        final int callingUid = Binder.getCallingUid();
7610        return new ParceledListSlice<>(queryIntentServicesInternal(
7611                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7612    }
7613
7614    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7615            String resolvedType, int flags, int userId, int callingUid,
7616            boolean includeInstantApps) {
7617        if (!sUserManager.exists(userId)) return Collections.emptyList();
7618        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7619                false /*requireFullPermission*/, false /*checkShell*/,
7620                "query intent receivers");
7621        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7622        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7623        ComponentName comp = intent.getComponent();
7624        if (comp == null) {
7625            if (intent.getSelector() != null) {
7626                intent = intent.getSelector();
7627                comp = intent.getComponent();
7628            }
7629        }
7630        if (comp != null) {
7631            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7632            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7633            if (si != null) {
7634                // When specifying an explicit component, we prevent the service from being
7635                // used when either 1) the service is in an instant application and the
7636                // caller is not the same instant application or 2) the calling package is
7637                // ephemeral and the activity is not visible to ephemeral applications.
7638                final boolean matchInstantApp =
7639                        (flags & PackageManager.MATCH_INSTANT) != 0;
7640                final boolean matchVisibleToInstantAppOnly =
7641                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7642                final boolean isCallerInstantApp =
7643                        instantAppPkgName != null;
7644                final boolean isTargetSameInstantApp =
7645                        comp.getPackageName().equals(instantAppPkgName);
7646                final boolean isTargetInstantApp =
7647                        (si.applicationInfo.privateFlags
7648                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7649                final boolean isTargetHiddenFromInstantApp =
7650                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7651                final boolean blockResolution =
7652                        !isTargetSameInstantApp
7653                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7654                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7655                                        && isTargetHiddenFromInstantApp));
7656                if (!blockResolution) {
7657                    final ResolveInfo ri = new ResolveInfo();
7658                    ri.serviceInfo = si;
7659                    list.add(ri);
7660                }
7661            }
7662            return list;
7663        }
7664
7665        // reader
7666        synchronized (mPackages) {
7667            String pkgName = intent.getPackage();
7668            if (pkgName == null) {
7669                return applyPostServiceResolutionFilter(
7670                        mServices.queryIntent(intent, resolvedType, flags, userId),
7671                        instantAppPkgName);
7672            }
7673            final PackageParser.Package pkg = mPackages.get(pkgName);
7674            if (pkg != null) {
7675                return applyPostServiceResolutionFilter(
7676                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7677                                userId),
7678                        instantAppPkgName);
7679            }
7680            return Collections.emptyList();
7681        }
7682    }
7683
7684    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7685            String instantAppPkgName) {
7686        if (instantAppPkgName == null) {
7687            return resolveInfos;
7688        }
7689        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7690            final ResolveInfo info = resolveInfos.get(i);
7691            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7692            // allow services that are defined in the provided package
7693            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7694                if (info.serviceInfo.splitName != null
7695                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7696                                info.serviceInfo.splitName)) {
7697                    // requested service is defined in a split that hasn't been installed yet.
7698                    // add the installer to the resolve list
7699                    if (DEBUG_INSTANT) {
7700                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7701                    }
7702                    final ResolveInfo installerInfo = new ResolveInfo(
7703                            mInstantAppInstallerInfo);
7704                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7705                            null /* installFailureActivity */,
7706                            info.serviceInfo.packageName,
7707                            info.serviceInfo.applicationInfo.longVersionCode,
7708                            info.serviceInfo.splitName);
7709                    // add a non-generic filter
7710                    installerInfo.filter = new IntentFilter();
7711                    // load resources from the correct package
7712                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7713                    resolveInfos.set(i, installerInfo);
7714                }
7715                continue;
7716            }
7717            // allow services that have been explicitly exposed to ephemeral apps
7718            if (!isEphemeralApp
7719                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7720                continue;
7721            }
7722            resolveInfos.remove(i);
7723        }
7724        return resolveInfos;
7725    }
7726
7727    @Override
7728    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7729            String resolvedType, int flags, int userId) {
7730        return new ParceledListSlice<>(
7731                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7732    }
7733
7734    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7735            Intent intent, String resolvedType, int flags, int userId) {
7736        if (!sUserManager.exists(userId)) return Collections.emptyList();
7737        final int callingUid = Binder.getCallingUid();
7738        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7739        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7740                false /*includeInstantApps*/);
7741        ComponentName comp = intent.getComponent();
7742        if (comp == null) {
7743            if (intent.getSelector() != null) {
7744                intent = intent.getSelector();
7745                comp = intent.getComponent();
7746            }
7747        }
7748        if (comp != null) {
7749            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7750            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7751            if (pi != null) {
7752                // When specifying an explicit component, we prevent the provider from being
7753                // used when either 1) the provider is in an instant application and the
7754                // caller is not the same instant application or 2) the calling package is an
7755                // instant application and the provider is not visible to instant applications.
7756                final boolean matchInstantApp =
7757                        (flags & PackageManager.MATCH_INSTANT) != 0;
7758                final boolean matchVisibleToInstantAppOnly =
7759                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7760                final boolean isCallerInstantApp =
7761                        instantAppPkgName != null;
7762                final boolean isTargetSameInstantApp =
7763                        comp.getPackageName().equals(instantAppPkgName);
7764                final boolean isTargetInstantApp =
7765                        (pi.applicationInfo.privateFlags
7766                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7767                final boolean isTargetHiddenFromInstantApp =
7768                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7769                final boolean blockResolution =
7770                        !isTargetSameInstantApp
7771                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7772                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7773                                        && isTargetHiddenFromInstantApp));
7774                if (!blockResolution) {
7775                    final ResolveInfo ri = new ResolveInfo();
7776                    ri.providerInfo = pi;
7777                    list.add(ri);
7778                }
7779            }
7780            return list;
7781        }
7782
7783        // reader
7784        synchronized (mPackages) {
7785            String pkgName = intent.getPackage();
7786            if (pkgName == null) {
7787                return applyPostContentProviderResolutionFilter(
7788                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7789                        instantAppPkgName);
7790            }
7791            final PackageParser.Package pkg = mPackages.get(pkgName);
7792            if (pkg != null) {
7793                return applyPostContentProviderResolutionFilter(
7794                        mProviders.queryIntentForPackage(
7795                        intent, resolvedType, flags, pkg.providers, userId),
7796                        instantAppPkgName);
7797            }
7798            return Collections.emptyList();
7799        }
7800    }
7801
7802    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7803            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7804        if (instantAppPkgName == null) {
7805            return resolveInfos;
7806        }
7807        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7808            final ResolveInfo info = resolveInfos.get(i);
7809            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7810            // allow providers that are defined in the provided package
7811            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7812                if (info.providerInfo.splitName != null
7813                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7814                                info.providerInfo.splitName)) {
7815                    // requested provider is defined in a split that hasn't been installed yet.
7816                    // add the installer to the resolve list
7817                    if (DEBUG_INSTANT) {
7818                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7819                    }
7820                    final ResolveInfo installerInfo = new ResolveInfo(
7821                            mInstantAppInstallerInfo);
7822                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7823                            null /*failureActivity*/,
7824                            info.providerInfo.packageName,
7825                            info.providerInfo.applicationInfo.longVersionCode,
7826                            info.providerInfo.splitName);
7827                    // add a non-generic filter
7828                    installerInfo.filter = new IntentFilter();
7829                    // load resources from the correct package
7830                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7831                    resolveInfos.set(i, installerInfo);
7832                }
7833                continue;
7834            }
7835            // allow providers that have been explicitly exposed to instant applications
7836            if (!isEphemeralApp
7837                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7838                continue;
7839            }
7840            resolveInfos.remove(i);
7841        }
7842        return resolveInfos;
7843    }
7844
7845    @Override
7846    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7847        final int callingUid = Binder.getCallingUid();
7848        if (getInstantAppPackageName(callingUid) != null) {
7849            return ParceledListSlice.emptyList();
7850        }
7851        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7852        flags = updateFlagsForPackage(flags, userId, null);
7853        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7854        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7855                true /* requireFullPermission */, false /* checkShell */,
7856                "get installed packages");
7857
7858        // writer
7859        synchronized (mPackages) {
7860            ArrayList<PackageInfo> list;
7861            if (listUninstalled) {
7862                list = new ArrayList<>(mSettings.mPackages.size());
7863                for (PackageSetting ps : mSettings.mPackages.values()) {
7864                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7865                        continue;
7866                    }
7867                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7868                        continue;
7869                    }
7870                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7871                    if (pi != null) {
7872                        list.add(pi);
7873                    }
7874                }
7875            } else {
7876                list = new ArrayList<>(mPackages.size());
7877                for (PackageParser.Package p : mPackages.values()) {
7878                    final PackageSetting ps = (PackageSetting) p.mExtras;
7879                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7880                        continue;
7881                    }
7882                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7883                        continue;
7884                    }
7885                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7886                            p.mExtras, flags, userId);
7887                    if (pi != null) {
7888                        list.add(pi);
7889                    }
7890                }
7891            }
7892
7893            return new ParceledListSlice<>(list);
7894        }
7895    }
7896
7897    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7898            String[] permissions, boolean[] tmp, int flags, int userId) {
7899        int numMatch = 0;
7900        final PermissionsState permissionsState = ps.getPermissionsState();
7901        for (int i=0; i<permissions.length; i++) {
7902            final String permission = permissions[i];
7903            if (permissionsState.hasPermission(permission, userId)) {
7904                tmp[i] = true;
7905                numMatch++;
7906            } else {
7907                tmp[i] = false;
7908            }
7909        }
7910        if (numMatch == 0) {
7911            return;
7912        }
7913        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7914
7915        // The above might return null in cases of uninstalled apps or install-state
7916        // skew across users/profiles.
7917        if (pi != null) {
7918            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7919                if (numMatch == permissions.length) {
7920                    pi.requestedPermissions = permissions;
7921                } else {
7922                    pi.requestedPermissions = new String[numMatch];
7923                    numMatch = 0;
7924                    for (int i=0; i<permissions.length; i++) {
7925                        if (tmp[i]) {
7926                            pi.requestedPermissions[numMatch] = permissions[i];
7927                            numMatch++;
7928                        }
7929                    }
7930                }
7931            }
7932            list.add(pi);
7933        }
7934    }
7935
7936    @Override
7937    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7938            String[] permissions, int flags, int userId) {
7939        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7940        flags = updateFlagsForPackage(flags, userId, permissions);
7941        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7942                true /* requireFullPermission */, false /* checkShell */,
7943                "get packages holding permissions");
7944        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7945
7946        // writer
7947        synchronized (mPackages) {
7948            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7949            boolean[] tmpBools = new boolean[permissions.length];
7950            if (listUninstalled) {
7951                for (PackageSetting ps : mSettings.mPackages.values()) {
7952                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7953                            userId);
7954                }
7955            } else {
7956                for (PackageParser.Package pkg : mPackages.values()) {
7957                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7958                    if (ps != null) {
7959                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7960                                userId);
7961                    }
7962                }
7963            }
7964
7965            return new ParceledListSlice<PackageInfo>(list);
7966        }
7967    }
7968
7969    @Override
7970    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7971        final int callingUid = Binder.getCallingUid();
7972        if (getInstantAppPackageName(callingUid) != null) {
7973            return ParceledListSlice.emptyList();
7974        }
7975        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7976        flags = updateFlagsForApplication(flags, userId, null);
7977        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7978
7979        // writer
7980        synchronized (mPackages) {
7981            ArrayList<ApplicationInfo> list;
7982            if (listUninstalled) {
7983                list = new ArrayList<>(mSettings.mPackages.size());
7984                for (PackageSetting ps : mSettings.mPackages.values()) {
7985                    ApplicationInfo ai;
7986                    int effectiveFlags = flags;
7987                    if (ps.isSystem()) {
7988                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7989                    }
7990                    if (ps.pkg != null) {
7991                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7992                            continue;
7993                        }
7994                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7995                            continue;
7996                        }
7997                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7998                                ps.readUserState(userId), userId);
7999                        if (ai != null) {
8000                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8001                        }
8002                    } else {
8003                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8004                        // and already converts to externally visible package name
8005                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8006                                callingUid, effectiveFlags, userId);
8007                    }
8008                    if (ai != null) {
8009                        list.add(ai);
8010                    }
8011                }
8012            } else {
8013                list = new ArrayList<>(mPackages.size());
8014                for (PackageParser.Package p : mPackages.values()) {
8015                    if (p.mExtras != null) {
8016                        PackageSetting ps = (PackageSetting) p.mExtras;
8017                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8018                            continue;
8019                        }
8020                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8021                            continue;
8022                        }
8023                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8024                                ps.readUserState(userId), userId);
8025                        if (ai != null) {
8026                            ai.packageName = resolveExternalPackageNameLPr(p);
8027                            list.add(ai);
8028                        }
8029                    }
8030                }
8031            }
8032
8033            return new ParceledListSlice<>(list);
8034        }
8035    }
8036
8037    @Override
8038    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8039        if (HIDE_EPHEMERAL_APIS) {
8040            return null;
8041        }
8042        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8043            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8044                    "getEphemeralApplications");
8045        }
8046        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8047                true /* requireFullPermission */, false /* checkShell */,
8048                "getEphemeralApplications");
8049        synchronized (mPackages) {
8050            List<InstantAppInfo> instantApps = mInstantAppRegistry
8051                    .getInstantAppsLPr(userId);
8052            if (instantApps != null) {
8053                return new ParceledListSlice<>(instantApps);
8054            }
8055        }
8056        return null;
8057    }
8058
8059    @Override
8060    public boolean isInstantApp(String packageName, int userId) {
8061        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8062                true /* requireFullPermission */, false /* checkShell */,
8063                "isInstantApp");
8064        if (HIDE_EPHEMERAL_APIS) {
8065            return false;
8066        }
8067
8068        synchronized (mPackages) {
8069            int callingUid = Binder.getCallingUid();
8070            if (Process.isIsolated(callingUid)) {
8071                callingUid = mIsolatedOwners.get(callingUid);
8072            }
8073            final PackageSetting ps = mSettings.mPackages.get(packageName);
8074            final boolean returnAllowed =
8075                    ps != null
8076                    && (isCallerSameApp(packageName, callingUid)
8077                            || canViewInstantApps(callingUid, userId)
8078                            || mInstantAppRegistry.isInstantAccessGranted(
8079                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8080            if (returnAllowed) {
8081                return ps.getInstantApp(userId);
8082            }
8083        }
8084        return false;
8085    }
8086
8087    @Override
8088    public byte[] getInstantAppCookie(String packageName, int userId) {
8089        if (HIDE_EPHEMERAL_APIS) {
8090            return null;
8091        }
8092
8093        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8094                true /* requireFullPermission */, false /* checkShell */,
8095                "getInstantAppCookie");
8096        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8097            return null;
8098        }
8099        synchronized (mPackages) {
8100            return mInstantAppRegistry.getInstantAppCookieLPw(
8101                    packageName, userId);
8102        }
8103    }
8104
8105    @Override
8106    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8107        if (HIDE_EPHEMERAL_APIS) {
8108            return true;
8109        }
8110
8111        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8112                true /* requireFullPermission */, true /* checkShell */,
8113                "setInstantAppCookie");
8114        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8115            return false;
8116        }
8117        synchronized (mPackages) {
8118            return mInstantAppRegistry.setInstantAppCookieLPw(
8119                    packageName, cookie, userId);
8120        }
8121    }
8122
8123    @Override
8124    public Bitmap getInstantAppIcon(String packageName, int userId) {
8125        if (HIDE_EPHEMERAL_APIS) {
8126            return null;
8127        }
8128
8129        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8130            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8131                    "getInstantAppIcon");
8132        }
8133        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8134                true /* requireFullPermission */, false /* checkShell */,
8135                "getInstantAppIcon");
8136
8137        synchronized (mPackages) {
8138            return mInstantAppRegistry.getInstantAppIconLPw(
8139                    packageName, userId);
8140        }
8141    }
8142
8143    private boolean isCallerSameApp(String packageName, int uid) {
8144        PackageParser.Package pkg = mSettings.getPackageLPr(packageName).getPackage();
8145        return pkg != null
8146                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8147    }
8148
8149    @Override
8150    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8151        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8152            return ParceledListSlice.emptyList();
8153        }
8154        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8155    }
8156
8157    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8158        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8159
8160        // reader
8161        synchronized (mPackages) {
8162            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8163            final int userId = UserHandle.getCallingUserId();
8164            while (i.hasNext()) {
8165                final PackageParser.Package p = i.next();
8166                if (p.applicationInfo == null) continue;
8167
8168                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8169                        && !p.applicationInfo.isDirectBootAware();
8170                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8171                        && p.applicationInfo.isDirectBootAware();
8172
8173                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8174                        && (!mSafeMode || isSystemApp(p))
8175                        && (matchesUnaware || matchesAware)) {
8176                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8177                    if (ps != null) {
8178                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8179                                ps.readUserState(userId), userId);
8180                        if (ai != null) {
8181                            finalList.add(ai);
8182                        }
8183                    }
8184                }
8185            }
8186        }
8187
8188        return finalList;
8189    }
8190
8191    @Override
8192    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8193        return resolveContentProviderInternal(name, flags, userId);
8194    }
8195
8196    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8197        if (!sUserManager.exists(userId)) return null;
8198        flags = updateFlagsForComponent(flags, userId, name);
8199        final int callingUid = Binder.getCallingUid();
8200        synchronized (mPackages) {
8201            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8202            PackageSetting ps = provider != null
8203                    ? mSettings.mPackages.get(provider.owner.packageName)
8204                    : null;
8205            if (ps != null) {
8206                // provider not enabled
8207                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8208                    return null;
8209                }
8210                final ComponentName component =
8211                        new ComponentName(provider.info.packageName, provider.info.name);
8212                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8213                    return null;
8214                }
8215                return PackageParser.generateProviderInfo(
8216                        provider, flags, ps.readUserState(userId), userId);
8217            }
8218            return null;
8219        }
8220    }
8221
8222    /**
8223     * @deprecated
8224     */
8225    @Deprecated
8226    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8227        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8228            return;
8229        }
8230        // reader
8231        synchronized (mPackages) {
8232            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8233                    .entrySet().iterator();
8234            final int userId = UserHandle.getCallingUserId();
8235            while (i.hasNext()) {
8236                Map.Entry<String, PackageParser.Provider> entry = i.next();
8237                PackageParser.Provider p = entry.getValue();
8238                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8239
8240                if (ps != null && p.syncable
8241                        && (!mSafeMode || (p.info.applicationInfo.flags
8242                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8243                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8244                            ps.readUserState(userId), userId);
8245                    if (info != null) {
8246                        outNames.add(entry.getKey());
8247                        outInfo.add(info);
8248                    }
8249                }
8250            }
8251        }
8252    }
8253
8254    @Override
8255    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8256            int uid, int flags, String metaDataKey) {
8257        final int callingUid = Binder.getCallingUid();
8258        final int userId = processName != null ? UserHandle.getUserId(uid)
8259                : UserHandle.getCallingUserId();
8260        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8261        flags = updateFlagsForComponent(flags, userId, processName);
8262        ArrayList<ProviderInfo> finalList = null;
8263        // reader
8264        synchronized (mPackages) {
8265            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8266            while (i.hasNext()) {
8267                final PackageParser.Provider p = i.next();
8268                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8269                if (ps != null && p.info.authority != null
8270                        && (processName == null
8271                                || (p.info.processName.equals(processName)
8272                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8273                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8274
8275                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8276                    // parameter.
8277                    if (metaDataKey != null
8278                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8279                        continue;
8280                    }
8281                    final ComponentName component =
8282                            new ComponentName(p.info.packageName, p.info.name);
8283                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8284                        continue;
8285                    }
8286                    if (finalList == null) {
8287                        finalList = new ArrayList<ProviderInfo>(3);
8288                    }
8289                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8290                            ps.readUserState(userId), userId);
8291                    if (info != null) {
8292                        finalList.add(info);
8293                    }
8294                }
8295            }
8296        }
8297
8298        if (finalList != null) {
8299            Collections.sort(finalList, mProviderInitOrderSorter);
8300            return new ParceledListSlice<ProviderInfo>(finalList);
8301        }
8302
8303        return ParceledListSlice.emptyList();
8304    }
8305
8306    @Override
8307    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8308        // reader
8309        synchronized (mPackages) {
8310            final int callingUid = Binder.getCallingUid();
8311            final int callingUserId = UserHandle.getUserId(callingUid);
8312            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8313            if (ps == null) return null;
8314            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8315                return null;
8316            }
8317            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8318            return PackageParser.generateInstrumentationInfo(i, flags);
8319        }
8320    }
8321
8322    @Override
8323    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8324            String targetPackage, int flags) {
8325        final int callingUid = Binder.getCallingUid();
8326        final int callingUserId = UserHandle.getUserId(callingUid);
8327        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8328        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8329            return ParceledListSlice.emptyList();
8330        }
8331        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8332    }
8333
8334    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8335            int flags) {
8336        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8337
8338        // reader
8339        synchronized (mPackages) {
8340            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8341            while (i.hasNext()) {
8342                final PackageParser.Instrumentation p = i.next();
8343                if (targetPackage == null
8344                        || targetPackage.equals(p.info.targetPackage)) {
8345                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8346                            flags);
8347                    if (ii != null) {
8348                        finalList.add(ii);
8349                    }
8350                }
8351            }
8352        }
8353
8354        return finalList;
8355    }
8356
8357    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8358        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8359        try {
8360            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8361        } finally {
8362            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8363        }
8364    }
8365
8366    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8367        final File[] files = scanDir.listFiles();
8368        if (ArrayUtils.isEmpty(files)) {
8369            Log.d(TAG, "No files in app dir " + scanDir);
8370            return;
8371        }
8372
8373        if (DEBUG_PACKAGE_SCANNING) {
8374            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8375                    + " flags=0x" + Integer.toHexString(parseFlags));
8376        }
8377        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8378                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8379                mParallelPackageParserCallback)) {
8380            // Submit files for parsing in parallel
8381            int fileCount = 0;
8382            for (File file : files) {
8383                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8384                        && !PackageInstallerService.isStageName(file.getName());
8385                if (!isPackage) {
8386                    // Ignore entries which are not packages
8387                    continue;
8388                }
8389                parallelPackageParser.submit(file, parseFlags);
8390                fileCount++;
8391            }
8392
8393            // Process results one by one
8394            for (; fileCount > 0; fileCount--) {
8395                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8396                Throwable throwable = parseResult.throwable;
8397                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8398
8399                if (throwable == null) {
8400                    // TODO(toddke): move lower in the scan chain
8401                    // Static shared libraries have synthetic package names
8402                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8403                        renameStaticSharedLibraryPackage(parseResult.pkg);
8404                    }
8405                    try {
8406                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8407                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8408                                    currentTime, null);
8409                        }
8410                    } catch (PackageManagerException e) {
8411                        errorCode = e.error;
8412                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8413                    }
8414                } else if (throwable instanceof PackageParser.PackageParserException) {
8415                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8416                            throwable;
8417                    errorCode = e.error;
8418                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8419                } else {
8420                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8421                            + parseResult.scanFile, throwable);
8422                }
8423
8424                // Delete invalid userdata apps
8425                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8426                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8427                    logCriticalInfo(Log.WARN,
8428                            "Deleting invalid package at " + parseResult.scanFile);
8429                    removeCodePathLI(parseResult.scanFile);
8430                }
8431            }
8432        }
8433    }
8434
8435    public static void reportSettingsProblem(int priority, String msg) {
8436        logCriticalInfo(priority, msg);
8437    }
8438
8439    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8440            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8441        // When upgrading from pre-N MR1, verify the package time stamp using the package
8442        // directory and not the APK file.
8443        final long lastModifiedTime = mIsPreNMR1Upgrade
8444                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8445        if (ps != null && !forceCollect
8446                && ps.codePathString.equals(pkg.codePath)
8447                && ps.timeStamp == lastModifiedTime
8448                && !isCompatSignatureUpdateNeeded(pkg)
8449                && !isRecoverSignatureUpdateNeeded(pkg)) {
8450            if (ps.signatures.mSigningDetails.signatures != null
8451                    && ps.signatures.mSigningDetails.signatures.length != 0
8452                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8453                            != SignatureSchemeVersion.UNKNOWN) {
8454                // Optimization: reuse the existing cached signing data
8455                // if the package appears to be unchanged.
8456                pkg.mSigningDetails =
8457                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8458                return;
8459            }
8460
8461            Slog.w(TAG, "PackageSetting for " + ps.name
8462                    + " is missing signatures.  Collecting certs again to recover them.");
8463        } else {
8464            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8465                    (forceCollect ? " (forced)" : ""));
8466        }
8467
8468        try {
8469            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8470            PackageParser.collectCertificates(pkg, skipVerify);
8471        } catch (PackageParserException e) {
8472            throw PackageManagerException.from(e);
8473        } finally {
8474            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8475        }
8476    }
8477
8478    /**
8479     *  Traces a package scan.
8480     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8481     */
8482    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8483            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8484        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8485        try {
8486            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8487        } finally {
8488            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8489        }
8490    }
8491
8492    /**
8493     *  Scans a package and returns the newly parsed package.
8494     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8495     */
8496    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8497            long currentTime, UserHandle user) throws PackageManagerException {
8498        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8499        PackageParser pp = new PackageParser();
8500        pp.setSeparateProcesses(mSeparateProcesses);
8501        pp.setOnlyCoreApps(mOnlyCore);
8502        pp.setDisplayMetrics(mMetrics);
8503        pp.setCallback(mPackageParserCallback);
8504
8505        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8506        final PackageParser.Package pkg;
8507        try {
8508            pkg = pp.parsePackage(scanFile, parseFlags);
8509        } catch (PackageParserException e) {
8510            throw PackageManagerException.from(e);
8511        } finally {
8512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8513        }
8514
8515        // Static shared libraries have synthetic package names
8516        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8517            renameStaticSharedLibraryPackage(pkg);
8518        }
8519
8520        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8521    }
8522
8523    /**
8524     *  Scans a package and returns the newly parsed package.
8525     *  @throws PackageManagerException on a parse error.
8526     */
8527    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8528            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8529            @Nullable UserHandle user)
8530                    throws PackageManagerException {
8531        // If the package has children and this is the first dive in the function
8532        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8533        // packages (parent and children) would be successfully scanned before the
8534        // actual scan since scanning mutates internal state and we want to atomically
8535        // install the package and its children.
8536        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8537            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8538                scanFlags |= SCAN_CHECK_ONLY;
8539            }
8540        } else {
8541            scanFlags &= ~SCAN_CHECK_ONLY;
8542        }
8543
8544        // Scan the parent
8545        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8546                scanFlags, currentTime, user);
8547
8548        // Scan the children
8549        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8550        for (int i = 0; i < childCount; i++) {
8551            PackageParser.Package childPackage = pkg.childPackages.get(i);
8552            addForInitLI(childPackage, parseFlags, scanFlags,
8553                    currentTime, user);
8554        }
8555
8556
8557        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8558            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8559        }
8560
8561        return scannedPkg;
8562    }
8563
8564    /**
8565     * Returns if full apk verification can be skipped for the whole package, including the splits.
8566     */
8567    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8568        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8569            return false;
8570        }
8571        // TODO: Allow base and splits to be verified individually.
8572        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8573            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8574                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8575                    return false;
8576                }
8577            }
8578        }
8579        return true;
8580    }
8581
8582    /**
8583     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8584     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8585     * match one in a trusted source, and should be done separately.
8586     */
8587    private boolean canSkipFullApkVerification(String apkPath) {
8588        byte[] rootHashObserved = null;
8589        try {
8590            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8591            if (rootHashObserved == null) {
8592                return false;  // APK does not contain Merkle tree root hash.
8593            }
8594            synchronized (mInstallLock) {
8595                // Returns whether the observed root hash matches what kernel has.
8596                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8597                return true;
8598            }
8599        } catch (InstallerException | IOException | DigestException |
8600                NoSuchAlgorithmException e) {
8601            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8602        }
8603        return false;
8604    }
8605
8606    /**
8607     * Adds a new package to the internal data structures during platform initialization.
8608     * <p>After adding, the package is known to the system and available for querying.
8609     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8610     * etc...], additional checks are performed. Basic verification [such as ensuring
8611     * matching signatures, checking version codes, etc...] occurs if the package is
8612     * identical to a previously known package. If the package fails a signature check,
8613     * the version installed on /data will be removed. If the version of the new package
8614     * is less than or equal than the version on /data, it will be ignored.
8615     * <p>Regardless of the package location, the results are applied to the internal
8616     * structures and the package is made available to the rest of the system.
8617     * <p>NOTE: The return value should be removed. It's the passed in package object.
8618     */
8619    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8620            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8621            @Nullable UserHandle user)
8622                    throws PackageManagerException {
8623        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8624        final String renamedPkgName;
8625        final PackageSetting disabledPkgSetting;
8626        final boolean isSystemPkgUpdated;
8627        final boolean pkgAlreadyExists;
8628        PackageSetting pkgSetting;
8629
8630        // NOTE: installPackageLI() has the same code to setup the package's
8631        // application info. This probably should be done lower in the call
8632        // stack [such as scanPackageOnly()]. However, we verify the application
8633        // info prior to that [in scanPackageNew()] and thus have to setup
8634        // the application info early.
8635        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8636        pkg.setApplicationInfoCodePath(pkg.codePath);
8637        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8638        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8639        pkg.setApplicationInfoResourcePath(pkg.codePath);
8640        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8641        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8642
8643        synchronized (mPackages) {
8644            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8645            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8646            if (realPkgName != null) {
8647                ensurePackageRenamed(pkg, renamedPkgName);
8648            }
8649            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8650            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8651            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8652            pkgAlreadyExists = pkgSetting != null;
8653            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8654            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8655            isSystemPkgUpdated = disabledPkgSetting != null;
8656
8657            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8658                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8659            }
8660
8661            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8662                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8663                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8664                    : null;
8665            if (DEBUG_PACKAGE_SCANNING
8666                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8667                    && sharedUserSetting != null) {
8668                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8669                        + " (uid=" + sharedUserSetting.userId + "):"
8670                        + " packages=" + sharedUserSetting.packages);
8671            }
8672
8673            if (scanSystemPartition) {
8674                // Potentially prune child packages. If the application on the /system
8675                // partition has been updated via OTA, but, is still disabled by a
8676                // version on /data, cycle through all of its children packages and
8677                // remove children that are no longer defined.
8678                if (isSystemPkgUpdated) {
8679                    final int scannedChildCount = (pkg.childPackages != null)
8680                            ? pkg.childPackages.size() : 0;
8681                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8682                            ? disabledPkgSetting.childPackageNames.size() : 0;
8683                    for (int i = 0; i < disabledChildCount; i++) {
8684                        String disabledChildPackageName =
8685                                disabledPkgSetting.childPackageNames.get(i);
8686                        boolean disabledPackageAvailable = false;
8687                        for (int j = 0; j < scannedChildCount; j++) {
8688                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8689                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8690                                disabledPackageAvailable = true;
8691                                break;
8692                            }
8693                        }
8694                        if (!disabledPackageAvailable) {
8695                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8696                        }
8697                    }
8698                    // we're updating the disabled package, so, scan it as the package setting
8699                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8700                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8701                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8702                            (pkg == mPlatformPackage), user);
8703                    applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
8704                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8705                }
8706            }
8707        }
8708
8709        final boolean newPkgChangedPaths =
8710                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8711        final boolean newPkgVersionGreater =
8712                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8713        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8714                && newPkgChangedPaths && newPkgVersionGreater;
8715        if (isSystemPkgBetter) {
8716            // The version of the application on /system is greater than the version on
8717            // /data. Switch back to the application on /system.
8718            // It's safe to assume the application on /system will correctly scan. If not,
8719            // there won't be a working copy of the application.
8720            synchronized (mPackages) {
8721                // just remove the loaded entries from package lists
8722                mPackages.remove(pkgSetting.name);
8723            }
8724
8725            logCriticalInfo(Log.WARN,
8726                    "System package updated;"
8727                    + " name: " + pkgSetting.name
8728                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8729                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8730
8731            final InstallArgs args = createInstallArgsForExisting(
8732                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8733                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8734            args.cleanUpResourcesLI();
8735            synchronized (mPackages) {
8736                mSettings.enableSystemPackageLPw(pkgSetting.name);
8737            }
8738        }
8739
8740        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8741            // The version of the application on the /system partition is less than or
8742            // equal to the version on the /data partition. Throw an exception and use
8743            // the application already installed on the /data partition.
8744            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8745                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8746                    + " better than this " + pkg.getLongVersionCode());
8747        }
8748
8749        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8750        // force re-collecting certificate.
8751        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8752                disabledPkgSetting);
8753        // Full APK verification can be skipped during certificate collection, only if the file is
8754        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8755        // cases, only data in Signing Block is verified instead of the whole file.
8756        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8757                (forceCollect && canSkipFullPackageVerification(pkg));
8758        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8759
8760        boolean shouldHideSystemApp = false;
8761        // A new application appeared on /system, but, we already have a copy of
8762        // the application installed on /data.
8763        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8764                && !pkgSetting.isSystem()) {
8765
8766            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8767                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8768                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8769                                    pkg.mSigningDetails,
8770                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8771                logCriticalInfo(Log.WARN,
8772                        "System package signature mismatch;"
8773                        + " name: " + pkgSetting.name);
8774                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8775                        "scanPackageInternalLI")) {
8776                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8777                }
8778                pkgSetting = null;
8779            } else if (newPkgVersionGreater) {
8780                // The application on /system is newer than the application on /data.
8781                // Simply remove the application on /data [keeping application data]
8782                // and replace it with the version on /system.
8783                logCriticalInfo(Log.WARN,
8784                        "System package enabled;"
8785                        + " name: " + pkgSetting.name
8786                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8787                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8788                InstallArgs args = createInstallArgsForExisting(
8789                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8790                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8791                synchronized (mInstallLock) {
8792                    args.cleanUpResourcesLI();
8793                }
8794            } else {
8795                // The application on /system is older than the application on /data. Hide
8796                // the application on /system and the version on /data will be scanned later
8797                // and re-added like an update.
8798                shouldHideSystemApp = true;
8799                logCriticalInfo(Log.INFO,
8800                        "System package disabled;"
8801                        + " name: " + pkgSetting.name
8802                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8803                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8804            }
8805        }
8806
8807        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8808                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8809
8810        if (shouldHideSystemApp) {
8811            synchronized (mPackages) {
8812                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8813            }
8814        }
8815        return scannedPkg;
8816    }
8817
8818    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8819        // Derive the new package synthetic package name
8820        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8821                + pkg.staticSharedLibVersion);
8822    }
8823
8824    private static String fixProcessName(String defProcessName,
8825            String processName) {
8826        if (processName == null) {
8827            return defProcessName;
8828        }
8829        return processName;
8830    }
8831
8832    /**
8833     * Enforces that only the system UID or root's UID can call a method exposed
8834     * via Binder.
8835     *
8836     * @param message used as message if SecurityException is thrown
8837     * @throws SecurityException if the caller is not system or root
8838     */
8839    private static final void enforceSystemOrRoot(String message) {
8840        final int uid = Binder.getCallingUid();
8841        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8842            throw new SecurityException(message);
8843        }
8844    }
8845
8846    @Override
8847    public void performFstrimIfNeeded() {
8848        enforceSystemOrRoot("Only the system can request fstrim");
8849
8850        // Before everything else, see whether we need to fstrim.
8851        try {
8852            IStorageManager sm = PackageHelper.getStorageManager();
8853            if (sm != null) {
8854                boolean doTrim = false;
8855                final long interval = android.provider.Settings.Global.getLong(
8856                        mContext.getContentResolver(),
8857                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8858                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8859                if (interval > 0) {
8860                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8861                    if (timeSinceLast > interval) {
8862                        doTrim = true;
8863                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8864                                + "; running immediately");
8865                    }
8866                }
8867                if (doTrim) {
8868                    final boolean dexOptDialogShown;
8869                    synchronized (mPackages) {
8870                        dexOptDialogShown = mDexOptDialogShown;
8871                    }
8872                    if (!isFirstBoot() && dexOptDialogShown) {
8873                        try {
8874                            ActivityManager.getService().showBootMessage(
8875                                    mContext.getResources().getString(
8876                                            R.string.android_upgrading_fstrim), true);
8877                        } catch (RemoteException e) {
8878                        }
8879                    }
8880                    sm.runMaintenance();
8881                }
8882            } else {
8883                Slog.e(TAG, "storageManager service unavailable!");
8884            }
8885        } catch (RemoteException e) {
8886            // Can't happen; StorageManagerService is local
8887        }
8888    }
8889
8890    @Override
8891    public void updatePackagesIfNeeded() {
8892        enforceSystemOrRoot("Only the system can request package update");
8893
8894        // We need to re-extract after an OTA.
8895        boolean causeUpgrade = isUpgrade();
8896
8897        // First boot or factory reset.
8898        // Note: we also handle devices that are upgrading to N right now as if it is their
8899        //       first boot, as they do not have profile data.
8900        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8901
8902        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8903        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8904
8905        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8906            return;
8907        }
8908
8909        List<PackageParser.Package> pkgs;
8910        synchronized (mPackages) {
8911            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8912        }
8913
8914        final long startTime = System.nanoTime();
8915        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8916                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8917                    false /* bootComplete */);
8918
8919        final int elapsedTimeSeconds =
8920                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8921
8922        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8923        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8924        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8925        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8926        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8927    }
8928
8929    /*
8930     * Return the prebuilt profile path given a package base code path.
8931     */
8932    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8933        return pkg.baseCodePath + ".prof";
8934    }
8935
8936    /**
8937     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8938     * containing statistics about the invocation. The array consists of three elements,
8939     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8940     * and {@code numberOfPackagesFailed}.
8941     */
8942    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8943            final int compilationReason, boolean bootComplete) {
8944
8945        int numberOfPackagesVisited = 0;
8946        int numberOfPackagesOptimized = 0;
8947        int numberOfPackagesSkipped = 0;
8948        int numberOfPackagesFailed = 0;
8949        final int numberOfPackagesToDexopt = pkgs.size();
8950
8951        for (PackageParser.Package pkg : pkgs) {
8952            numberOfPackagesVisited++;
8953
8954            boolean useProfileForDexopt = false;
8955
8956            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8957                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8958                // that are already compiled.
8959                File profileFile = new File(getPrebuildProfilePath(pkg));
8960                // Copy profile if it exists.
8961                if (profileFile.exists()) {
8962                    try {
8963                        // We could also do this lazily before calling dexopt in
8964                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8965                        // is that we don't have a good way to say "do this only once".
8966                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8967                                pkg.applicationInfo.uid, pkg.packageName,
8968                                ArtManager.getProfileName(null))) {
8969                            Log.e(TAG, "Installer failed to copy system profile!");
8970                        } else {
8971                            // Disabled as this causes speed-profile compilation during first boot
8972                            // even if things are already compiled.
8973                            // useProfileForDexopt = true;
8974                        }
8975                    } catch (Exception e) {
8976                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8977                                e);
8978                    }
8979                } else {
8980                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8981                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8982                    // minimize the number off apps being speed-profile compiled during first boot.
8983                    // The other paths will not change the filter.
8984                    if (disabledPs != null && disabledPs.pkg.isStub) {
8985                        // The package is the stub one, remove the stub suffix to get the normal
8986                        // package and APK names.
8987                        String systemProfilePath =
8988                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8989                        profileFile = new File(systemProfilePath);
8990                        // If we have a profile for a compressed APK, copy it to the reference
8991                        // location.
8992                        // Note that copying the profile here will cause it to override the
8993                        // reference profile every OTA even though the existing reference profile
8994                        // may have more data. We can't copy during decompression since the
8995                        // directories are not set up at that point.
8996                        if (profileFile.exists()) {
8997                            try {
8998                                // We could also do this lazily before calling dexopt in
8999                                // PackageDexOptimizer to prevent this happening on first boot. The
9000                                // issue is that we don't have a good way to say "do this only
9001                                // once".
9002                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9003                                        pkg.applicationInfo.uid, pkg.packageName,
9004                                        ArtManager.getProfileName(null))) {
9005                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9006                                } else {
9007                                    useProfileForDexopt = true;
9008                                }
9009                            } catch (Exception e) {
9010                                Log.e(TAG, "Failed to copy profile " +
9011                                        profileFile.getAbsolutePath() + " ", e);
9012                            }
9013                        }
9014                    }
9015                }
9016            }
9017
9018            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9019                if (DEBUG_DEXOPT) {
9020                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9021                }
9022                numberOfPackagesSkipped++;
9023                continue;
9024            }
9025
9026            if (DEBUG_DEXOPT) {
9027                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9028                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9029            }
9030
9031            if (showDialog) {
9032                try {
9033                    ActivityManager.getService().showBootMessage(
9034                            mContext.getResources().getString(R.string.android_upgrading_apk,
9035                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9036                } catch (RemoteException e) {
9037                }
9038                synchronized (mPackages) {
9039                    mDexOptDialogShown = true;
9040                }
9041            }
9042
9043            int pkgCompilationReason = compilationReason;
9044            if (useProfileForDexopt) {
9045                // Use background dexopt mode to try and use the profile. Note that this does not
9046                // guarantee usage of the profile.
9047                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9048            }
9049
9050            // checkProfiles is false to avoid merging profiles during boot which
9051            // might interfere with background compilation (b/28612421).
9052            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9053            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9054            // trade-off worth doing to save boot time work.
9055            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9056            if (compilationReason == REASON_FIRST_BOOT) {
9057                // TODO: This doesn't cover the upgrade case, we should check for this too.
9058                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9059            }
9060            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9061                    pkg.packageName,
9062                    pkgCompilationReason,
9063                    dexoptFlags));
9064
9065            switch (primaryDexOptStaus) {
9066                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9067                    numberOfPackagesOptimized++;
9068                    break;
9069                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9070                    numberOfPackagesSkipped++;
9071                    break;
9072                case PackageDexOptimizer.DEX_OPT_FAILED:
9073                    numberOfPackagesFailed++;
9074                    break;
9075                default:
9076                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9077                    break;
9078            }
9079        }
9080
9081        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9082                numberOfPackagesFailed };
9083    }
9084
9085    @Override
9086    public void notifyPackageUse(String packageName, int reason) {
9087        synchronized (mPackages) {
9088            final int callingUid = Binder.getCallingUid();
9089            final int callingUserId = UserHandle.getUserId(callingUid);
9090            if (getInstantAppPackageName(callingUid) != null) {
9091                if (!isCallerSameApp(packageName, callingUid)) {
9092                    return;
9093                }
9094            } else {
9095                if (isInstantApp(packageName, callingUserId)) {
9096                    return;
9097                }
9098            }
9099            notifyPackageUseLocked(packageName, reason);
9100        }
9101    }
9102
9103    @GuardedBy("mPackages")
9104    private void notifyPackageUseLocked(String packageName, int reason) {
9105        final PackageParser.Package p = mPackages.get(packageName);
9106        if (p == null) {
9107            return;
9108        }
9109        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9110    }
9111
9112    @Override
9113    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9114            List<String> classPaths, String loaderIsa) {
9115        int userId = UserHandle.getCallingUserId();
9116        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9117        if (ai == null) {
9118            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9119                + loadingPackageName + ", user=" + userId);
9120            return;
9121        }
9122        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9123    }
9124
9125    @Override
9126    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9127            IDexModuleRegisterCallback callback) {
9128        int userId = UserHandle.getCallingUserId();
9129        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9130        DexManager.RegisterDexModuleResult result;
9131        if (ai == null) {
9132            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9133                     " calling user. package=" + packageName + ", user=" + userId);
9134            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9135        } else {
9136            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9137        }
9138
9139        if (callback != null) {
9140            mHandler.post(() -> {
9141                try {
9142                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9143                } catch (RemoteException e) {
9144                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9145                }
9146            });
9147        }
9148    }
9149
9150    /**
9151     * Ask the package manager to perform a dex-opt with the given compiler filter.
9152     *
9153     * Note: exposed only for the shell command to allow moving packages explicitly to a
9154     *       definite state.
9155     */
9156    @Override
9157    public boolean performDexOptMode(String packageName,
9158            boolean checkProfiles, String targetCompilerFilter, boolean force,
9159            boolean bootComplete, String splitName) {
9160        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9161                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9162                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9163        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9164                targetCompilerFilter, splitName, flags));
9165    }
9166
9167    /**
9168     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9169     * secondary dex files belonging to the given package.
9170     *
9171     * Note: exposed only for the shell command to allow moving packages explicitly to a
9172     *       definite state.
9173     */
9174    @Override
9175    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9176            boolean force) {
9177        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9178                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9179                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9180                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9181        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9182    }
9183
9184    /*package*/ boolean performDexOpt(DexoptOptions options) {
9185        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9186            return false;
9187        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9188            return false;
9189        }
9190
9191        if (options.isDexoptOnlySecondaryDex()) {
9192            return mDexManager.dexoptSecondaryDex(options);
9193        } else {
9194            int dexoptStatus = performDexOptWithStatus(options);
9195            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9196        }
9197    }
9198
9199    /**
9200     * Perform dexopt on the given package and return one of following result:
9201     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9202     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9203     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9204     */
9205    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9206        return performDexOptTraced(options);
9207    }
9208
9209    private int performDexOptTraced(DexoptOptions options) {
9210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9211        try {
9212            return performDexOptInternal(options);
9213        } finally {
9214            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9215        }
9216    }
9217
9218    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9219    // if the package can now be considered up to date for the given filter.
9220    private int performDexOptInternal(DexoptOptions options) {
9221        PackageParser.Package p;
9222        synchronized (mPackages) {
9223            p = mPackages.get(options.getPackageName());
9224            if (p == null) {
9225                // Package could not be found. Report failure.
9226                return PackageDexOptimizer.DEX_OPT_FAILED;
9227            }
9228            mPackageUsage.maybeWriteAsync(mPackages);
9229            mCompilerStats.maybeWriteAsync();
9230        }
9231        long callingId = Binder.clearCallingIdentity();
9232        try {
9233            synchronized (mInstallLock) {
9234                return performDexOptInternalWithDependenciesLI(p, options);
9235            }
9236        } finally {
9237            Binder.restoreCallingIdentity(callingId);
9238        }
9239    }
9240
9241    public ArraySet<String> getOptimizablePackages() {
9242        ArraySet<String> pkgs = new ArraySet<String>();
9243        synchronized (mPackages) {
9244            for (PackageParser.Package p : mPackages.values()) {
9245                if (PackageDexOptimizer.canOptimizePackage(p)) {
9246                    pkgs.add(p.packageName);
9247                }
9248            }
9249        }
9250        return pkgs;
9251    }
9252
9253    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9254            DexoptOptions options) {
9255        // Select the dex optimizer based on the force parameter.
9256        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9257        //       allocate an object here.
9258        PackageDexOptimizer pdo = options.isForce()
9259                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9260                : mPackageDexOptimizer;
9261
9262        // Dexopt all dependencies first. Note: we ignore the return value and march on
9263        // on errors.
9264        // Note that we are going to call performDexOpt on those libraries as many times as
9265        // they are referenced in packages. When we do a batch of performDexOpt (for example
9266        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9267        // and the first package that uses the library will dexopt it. The
9268        // others will see that the compiled code for the library is up to date.
9269        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9270        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9271        if (!deps.isEmpty()) {
9272            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9273                    options.getCompilationReason(), options.getCompilerFilter(),
9274                    options.getSplitName(),
9275                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9276            for (PackageParser.Package depPackage : deps) {
9277                // TODO: Analyze and investigate if we (should) profile libraries.
9278                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9279                        getOrCreateCompilerPackageStats(depPackage),
9280                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9281            }
9282        }
9283        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9284                getOrCreateCompilerPackageStats(p),
9285                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9286    }
9287
9288    /**
9289     * Reconcile the information we have about the secondary dex files belonging to
9290     * {@code packagName} and the actual dex files. For all dex files that were
9291     * deleted, update the internal records and delete the generated oat files.
9292     */
9293    @Override
9294    public void reconcileSecondaryDexFiles(String packageName) {
9295        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9296            return;
9297        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9298            return;
9299        }
9300        mDexManager.reconcileSecondaryDexFiles(packageName);
9301    }
9302
9303    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9304    // a reference there.
9305    /*package*/ DexManager getDexManager() {
9306        return mDexManager;
9307    }
9308
9309    /**
9310     * Execute the background dexopt job immediately.
9311     */
9312    @Override
9313    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9314        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9315            return false;
9316        }
9317        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9318    }
9319
9320    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9321        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9322                || p.usesStaticLibraries != null) {
9323            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9324            Set<String> collectedNames = new HashSet<>();
9325            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9326
9327            retValue.remove(p);
9328
9329            return retValue;
9330        } else {
9331            return Collections.emptyList();
9332        }
9333    }
9334
9335    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9336            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9337        if (!collectedNames.contains(p.packageName)) {
9338            collectedNames.add(p.packageName);
9339            collected.add(p);
9340
9341            if (p.usesLibraries != null) {
9342                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9343                        null, collected, collectedNames);
9344            }
9345            if (p.usesOptionalLibraries != null) {
9346                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9347                        null, collected, collectedNames);
9348            }
9349            if (p.usesStaticLibraries != null) {
9350                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9351                        p.usesStaticLibrariesVersions, collected, collectedNames);
9352            }
9353        }
9354    }
9355
9356    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9357            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9358        final int libNameCount = libs.size();
9359        for (int i = 0; i < libNameCount; i++) {
9360            String libName = libs.get(i);
9361            long version = (versions != null && versions.length == libNameCount)
9362                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9363            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9364            if (libPkg != null) {
9365                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9366            }
9367        }
9368    }
9369
9370    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9371        synchronized (mPackages) {
9372            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9373            if (libEntry != null) {
9374                return mPackages.get(libEntry.apk);
9375            }
9376            return null;
9377        }
9378    }
9379
9380    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9381        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9382        if (versionedLib == null) {
9383            return null;
9384        }
9385        return versionedLib.get(version);
9386    }
9387
9388    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9389        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9390                pkg.staticSharedLibName);
9391        if (versionedLib == null) {
9392            return null;
9393        }
9394        long previousLibVersion = -1;
9395        final int versionCount = versionedLib.size();
9396        for (int i = 0; i < versionCount; i++) {
9397            final long libVersion = versionedLib.keyAt(i);
9398            if (libVersion < pkg.staticSharedLibVersion) {
9399                previousLibVersion = Math.max(previousLibVersion, libVersion);
9400            }
9401        }
9402        if (previousLibVersion >= 0) {
9403            return versionedLib.get(previousLibVersion);
9404        }
9405        return null;
9406    }
9407
9408    public void shutdown() {
9409        mPackageUsage.writeNow(mPackages);
9410        mCompilerStats.writeNow();
9411        mDexManager.writePackageDexUsageNow();
9412    }
9413
9414    @Override
9415    public void dumpProfiles(String packageName) {
9416        PackageParser.Package pkg;
9417        synchronized (mPackages) {
9418            pkg = mPackages.get(packageName);
9419            if (pkg == null) {
9420                throw new IllegalArgumentException("Unknown package: " + packageName);
9421            }
9422        }
9423        /* Only the shell, root, or the app user should be able to dump profiles. */
9424        int callingUid = Binder.getCallingUid();
9425        if (callingUid != Process.SHELL_UID &&
9426            callingUid != Process.ROOT_UID &&
9427            callingUid != pkg.applicationInfo.uid) {
9428            throw new SecurityException("dumpProfiles");
9429        }
9430
9431        synchronized (mInstallLock) {
9432            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9433            mArtManagerService.dumpProfiles(pkg);
9434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9435        }
9436    }
9437
9438    @Override
9439    public void forceDexOpt(String packageName) {
9440        enforceSystemOrRoot("forceDexOpt");
9441
9442        PackageParser.Package pkg;
9443        synchronized (mPackages) {
9444            pkg = mPackages.get(packageName);
9445            if (pkg == null) {
9446                throw new IllegalArgumentException("Unknown package: " + packageName);
9447            }
9448        }
9449
9450        synchronized (mInstallLock) {
9451            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9452
9453            // Whoever is calling forceDexOpt wants a compiled package.
9454            // Don't use profiles since that may cause compilation to be skipped.
9455            final int res = performDexOptInternalWithDependenciesLI(
9456                    pkg,
9457                    new DexoptOptions(packageName,
9458                            getDefaultCompilerFilter(),
9459                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9460
9461            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9462            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9463                throw new IllegalStateException("Failed to dexopt: " + res);
9464            }
9465        }
9466    }
9467
9468    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9469        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9470            Slog.w(TAG, "Unable to update from " + oldPkg.name
9471                    + " to " + newPkg.packageName
9472                    + ": old package not in system partition");
9473            return false;
9474        } else if (mPackages.get(oldPkg.name) != null) {
9475            Slog.w(TAG, "Unable to update from " + oldPkg.name
9476                    + " to " + newPkg.packageName
9477                    + ": old package still exists");
9478            return false;
9479        }
9480        return true;
9481    }
9482
9483    void removeCodePathLI(File codePath) {
9484        if (codePath.isDirectory()) {
9485            try {
9486                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9487            } catch (InstallerException e) {
9488                Slog.w(TAG, "Failed to remove code path", e);
9489            }
9490        } else {
9491            codePath.delete();
9492        }
9493    }
9494
9495    private int[] resolveUserIds(int userId) {
9496        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9497    }
9498
9499    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9500        if (pkg == null) {
9501            Slog.wtf(TAG, "Package was null!", new Throwable());
9502            return;
9503        }
9504        clearAppDataLeafLIF(pkg, userId, flags);
9505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9506        for (int i = 0; i < childCount; i++) {
9507            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9508        }
9509
9510        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9511    }
9512
9513    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9514        final PackageSetting ps;
9515        synchronized (mPackages) {
9516            ps = mSettings.mPackages.get(pkg.packageName);
9517        }
9518        for (int realUserId : resolveUserIds(userId)) {
9519            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9520            try {
9521                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9522                        ceDataInode);
9523            } catch (InstallerException e) {
9524                Slog.w(TAG, String.valueOf(e));
9525            }
9526        }
9527    }
9528
9529    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9530        if (pkg == null) {
9531            Slog.wtf(TAG, "Package was null!", new Throwable());
9532            return;
9533        }
9534        destroyAppDataLeafLIF(pkg, userId, flags);
9535        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9536        for (int i = 0; i < childCount; i++) {
9537            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9538        }
9539    }
9540
9541    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9542        final PackageSetting ps;
9543        synchronized (mPackages) {
9544            ps = mSettings.mPackages.get(pkg.packageName);
9545        }
9546        for (int realUserId : resolveUserIds(userId)) {
9547            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9548            try {
9549                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9550                        ceDataInode);
9551            } catch (InstallerException e) {
9552                Slog.w(TAG, String.valueOf(e));
9553            }
9554            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9555        }
9556    }
9557
9558    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9559        if (pkg == null) {
9560            Slog.wtf(TAG, "Package was null!", new Throwable());
9561            return;
9562        }
9563        destroyAppProfilesLeafLIF(pkg);
9564        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9565        for (int i = 0; i < childCount; i++) {
9566            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9567        }
9568    }
9569
9570    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9571        try {
9572            mInstaller.destroyAppProfiles(pkg.packageName);
9573        } catch (InstallerException e) {
9574            Slog.w(TAG, String.valueOf(e));
9575        }
9576    }
9577
9578    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9579        if (pkg == null) {
9580            Slog.wtf(TAG, "Package was null!", new Throwable());
9581            return;
9582        }
9583        mArtManagerService.clearAppProfiles(pkg);
9584        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9585        for (int i = 0; i < childCount; i++) {
9586            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9587        }
9588    }
9589
9590    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9591            long lastUpdateTime) {
9592        // Set parent install/update time
9593        PackageSetting ps = (PackageSetting) pkg.mExtras;
9594        if (ps != null) {
9595            ps.firstInstallTime = firstInstallTime;
9596            ps.lastUpdateTime = lastUpdateTime;
9597        }
9598        // Set children install/update time
9599        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9600        for (int i = 0; i < childCount; i++) {
9601            PackageParser.Package childPkg = pkg.childPackages.get(i);
9602            ps = (PackageSetting) childPkg.mExtras;
9603            if (ps != null) {
9604                ps.firstInstallTime = firstInstallTime;
9605                ps.lastUpdateTime = lastUpdateTime;
9606            }
9607        }
9608    }
9609
9610    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9611            SharedLibraryEntry file,
9612            PackageParser.Package changingLib) {
9613        if (file.path != null) {
9614            usesLibraryFiles.add(file.path);
9615            return;
9616        }
9617        PackageParser.Package p = mPackages.get(file.apk);
9618        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9619            // If we are doing this while in the middle of updating a library apk,
9620            // then we need to make sure to use that new apk for determining the
9621            // dependencies here.  (We haven't yet finished committing the new apk
9622            // to the package manager state.)
9623            if (p == null || p.packageName.equals(changingLib.packageName)) {
9624                p = changingLib;
9625            }
9626        }
9627        if (p != null) {
9628            usesLibraryFiles.addAll(p.getAllCodePaths());
9629            if (p.usesLibraryFiles != null) {
9630                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9631            }
9632        }
9633    }
9634
9635    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9636            PackageParser.Package changingLib) throws PackageManagerException {
9637        if (pkg == null) {
9638            return;
9639        }
9640        // The collection used here must maintain the order of addition (so
9641        // that libraries are searched in the correct order) and must have no
9642        // duplicates.
9643        Set<String> usesLibraryFiles = null;
9644        if (pkg.usesLibraries != null) {
9645            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9646                    null, null, pkg.packageName, changingLib, true,
9647                    pkg.applicationInfo.targetSdkVersion, null);
9648        }
9649        if (pkg.usesStaticLibraries != null) {
9650            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9651                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9652                    pkg.packageName, changingLib, true,
9653                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9654        }
9655        if (pkg.usesOptionalLibraries != null) {
9656            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9657                    null, null, pkg.packageName, changingLib, false,
9658                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9659        }
9660        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9661            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9662        } else {
9663            pkg.usesLibraryFiles = null;
9664        }
9665    }
9666
9667    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9668            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9669            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9670            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9671            throws PackageManagerException {
9672        final int libCount = requestedLibraries.size();
9673        for (int i = 0; i < libCount; i++) {
9674            final String libName = requestedLibraries.get(i);
9675            final long libVersion = requiredVersions != null ? requiredVersions[i]
9676                    : SharedLibraryInfo.VERSION_UNDEFINED;
9677            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9678            if (libEntry == null) {
9679                if (required) {
9680                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9681                            "Package " + packageName + " requires unavailable shared library "
9682                                    + libName + "; failing!");
9683                } else if (DEBUG_SHARED_LIBRARIES) {
9684                    Slog.i(TAG, "Package " + packageName
9685                            + " desires unavailable shared library "
9686                            + libName + "; ignoring!");
9687                }
9688            } else {
9689                if (requiredVersions != null && requiredCertDigests != null) {
9690                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9691                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9692                            "Package " + packageName + " requires unavailable static shared"
9693                                    + " library " + libName + " version "
9694                                    + libEntry.info.getLongVersion() + "; failing!");
9695                    }
9696
9697                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9698                    if (libPkg == null) {
9699                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9700                                "Package " + packageName + " requires unavailable static shared"
9701                                        + " library; failing!");
9702                    }
9703
9704                    final String[] expectedCertDigests = requiredCertDigests[i];
9705
9706
9707                    if (expectedCertDigests.length > 1) {
9708
9709                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9710                        final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
9711                                ? PackageUtils.computeSignaturesSha256Digests(
9712                                libPkg.mSigningDetails.signatures)
9713                                : PackageUtils.computeSignaturesSha256Digests(
9714                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9715
9716                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9717                        // target O we don't parse the "additional-certificate" tags similarly
9718                        // how we only consider all certs only for apps targeting O (see above).
9719                        // Therefore, the size check is safe to make.
9720                        if (expectedCertDigests.length != libCertDigests.length) {
9721                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9722                                    "Package " + packageName + " requires differently signed" +
9723                                            " static shared library; failing!");
9724                        }
9725
9726                        // Use a predictable order as signature order may vary
9727                        Arrays.sort(libCertDigests);
9728                        Arrays.sort(expectedCertDigests);
9729
9730                        final int certCount = libCertDigests.length;
9731                        for (int j = 0; j < certCount; j++) {
9732                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9733                                throw new PackageManagerException(
9734                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9735                                        "Package " + packageName + " requires differently signed" +
9736                                                " static shared library; failing!");
9737                            }
9738                        }
9739                    } else {
9740
9741                        // lib signing cert could have rotated beyond the one expected, check to see
9742                        // if the new one has been blessed by the old
9743                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9744                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9745                            throw new PackageManagerException(
9746                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9747                                    "Package " + packageName + " requires differently signed" +
9748                                            " static shared library; failing!");
9749                        }
9750                    }
9751                }
9752
9753                if (outUsedLibraries == null) {
9754                    // Use LinkedHashSet to preserve the order of files added to
9755                    // usesLibraryFiles while eliminating duplicates.
9756                    outUsedLibraries = new LinkedHashSet<>();
9757                }
9758                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9759            }
9760        }
9761        return outUsedLibraries;
9762    }
9763
9764    private static boolean hasString(List<String> list, List<String> which) {
9765        if (list == null) {
9766            return false;
9767        }
9768        for (int i=list.size()-1; i>=0; i--) {
9769            for (int j=which.size()-1; j>=0; j--) {
9770                if (which.get(j).equals(list.get(i))) {
9771                    return true;
9772                }
9773            }
9774        }
9775        return false;
9776    }
9777
9778    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9779            PackageParser.Package changingPkg) {
9780        ArrayList<PackageParser.Package> res = null;
9781        for (PackageParser.Package pkg : mPackages.values()) {
9782            if (changingPkg != null
9783                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9784                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9785                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9786                            changingPkg.staticSharedLibName)) {
9787                return null;
9788            }
9789            if (res == null) {
9790                res = new ArrayList<>();
9791            }
9792            res.add(pkg);
9793            try {
9794                updateSharedLibrariesLPr(pkg, changingPkg);
9795            } catch (PackageManagerException e) {
9796                // If a system app update or an app and a required lib missing we
9797                // delete the package and for updated system apps keep the data as
9798                // it is better for the user to reinstall than to be in an limbo
9799                // state. Also libs disappearing under an app should never happen
9800                // - just in case.
9801                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9802                    final int flags = pkg.isUpdatedSystemApp()
9803                            ? PackageManager.DELETE_KEEP_DATA : 0;
9804                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9805                            flags , null, true, null);
9806                }
9807                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9808            }
9809        }
9810        return res;
9811    }
9812
9813    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9814            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9815            @Nullable UserHandle user) throws PackageManagerException {
9816        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9817        // If the package has children and this is the first dive in the function
9818        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9819        // whether all packages (parent and children) would be successfully scanned
9820        // before the actual scan since scanning mutates internal state and we want
9821        // to atomically install the package and its children.
9822        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9823            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9824                scanFlags |= SCAN_CHECK_ONLY;
9825            }
9826        } else {
9827            scanFlags &= ~SCAN_CHECK_ONLY;
9828        }
9829
9830        final PackageParser.Package scannedPkg;
9831        try {
9832            // Scan the parent
9833            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9834            // Scan the children
9835            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9836            for (int i = 0; i < childCount; i++) {
9837                PackageParser.Package childPkg = pkg.childPackages.get(i);
9838                scanPackageNewLI(childPkg, parseFlags,
9839                        scanFlags, currentTime, user);
9840            }
9841        } finally {
9842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9843        }
9844
9845        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9846            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9847        }
9848
9849        return scannedPkg;
9850    }
9851
9852    /** The result of a package scan. */
9853    private static class ScanResult {
9854        /** Whether or not the package scan was successful */
9855        public final boolean success;
9856        /**
9857         * The final package settings. This may be the same object passed in
9858         * the {@link ScanRequest}, but, with modified values.
9859         */
9860        @Nullable public final PackageSetting pkgSetting;
9861        /** ABI code paths that have changed in the package scan */
9862        @Nullable public final List<String> changedAbiCodePath;
9863        public ScanResult(
9864                boolean success,
9865                @Nullable PackageSetting pkgSetting,
9866                @Nullable List<String> changedAbiCodePath) {
9867            this.success = success;
9868            this.pkgSetting = pkgSetting;
9869            this.changedAbiCodePath = changedAbiCodePath;
9870        }
9871    }
9872
9873    /** A package to be scanned */
9874    private static class ScanRequest {
9875        /** The parsed package */
9876        @NonNull public final PackageParser.Package pkg;
9877        /** Shared user settings, if the package has a shared user */
9878        @Nullable public final SharedUserSetting sharedUserSetting;
9879        /**
9880         * Package settings of the currently installed version.
9881         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9882         * during scan.
9883         */
9884        @Nullable public final PackageSetting pkgSetting;
9885        /** A copy of the settings for the currently installed version */
9886        @Nullable public final PackageSetting oldPkgSetting;
9887        /** Package settings for the disabled version on the /system partition */
9888        @Nullable public final PackageSetting disabledPkgSetting;
9889        /** Package settings for the installed version under its original package name */
9890        @Nullable public final PackageSetting originalPkgSetting;
9891        /** The real package name of a renamed application */
9892        @Nullable public final String realPkgName;
9893        public final @ParseFlags int parseFlags;
9894        public final @ScanFlags int scanFlags;
9895        /** The user for which the package is being scanned */
9896        @Nullable public final UserHandle user;
9897        /** Whether or not the platform package is being scanned */
9898        public final boolean isPlatformPackage;
9899        public ScanRequest(
9900                @NonNull PackageParser.Package pkg,
9901                @Nullable SharedUserSetting sharedUserSetting,
9902                @Nullable PackageSetting pkgSetting,
9903                @Nullable PackageSetting disabledPkgSetting,
9904                @Nullable PackageSetting originalPkgSetting,
9905                @Nullable String realPkgName,
9906                @ParseFlags int parseFlags,
9907                @ScanFlags int scanFlags,
9908                boolean isPlatformPackage,
9909                @Nullable UserHandle user) {
9910            this.pkg = pkg;
9911            this.pkgSetting = pkgSetting;
9912            this.sharedUserSetting = sharedUserSetting;
9913            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9914            this.disabledPkgSetting = disabledPkgSetting;
9915            this.originalPkgSetting = originalPkgSetting;
9916            this.realPkgName = realPkgName;
9917            this.parseFlags = parseFlags;
9918            this.scanFlags = scanFlags;
9919            this.isPlatformPackage = isPlatformPackage;
9920            this.user = user;
9921        }
9922    }
9923
9924    /**
9925     * Returns the actual scan flags depending upon the state of the other settings.
9926     * <p>Updated system applications will not have the following flags set
9927     * by default and need to be adjusted after the fact:
9928     * <ul>
9929     * <li>{@link #SCAN_AS_SYSTEM}</li>
9930     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9931     * <li>{@link #SCAN_AS_OEM}</li>
9932     * <li>{@link #SCAN_AS_VENDOR}</li>
9933     * <li>{@link #SCAN_AS_PRODUCT}</li>
9934     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9935     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9936     * </ul>
9937     */
9938    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9939            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9940            PackageParser.Package pkg) {
9941        if (disabledPkgSetting != null) {
9942            // updated system application, must at least have SCAN_AS_SYSTEM
9943            scanFlags |= SCAN_AS_SYSTEM;
9944            if ((disabledPkgSetting.pkgPrivateFlags
9945                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9946                scanFlags |= SCAN_AS_PRIVILEGED;
9947            }
9948            if ((disabledPkgSetting.pkgPrivateFlags
9949                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9950                scanFlags |= SCAN_AS_OEM;
9951            }
9952            if ((disabledPkgSetting.pkgPrivateFlags
9953                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9954                scanFlags |= SCAN_AS_VENDOR;
9955            }
9956            if ((disabledPkgSetting.pkgPrivateFlags
9957                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9958                scanFlags |= SCAN_AS_PRODUCT;
9959            }
9960        }
9961        if (pkgSetting != null) {
9962            final int userId = ((user == null) ? 0 : user.getIdentifier());
9963            if (pkgSetting.getInstantApp(userId)) {
9964                scanFlags |= SCAN_AS_INSTANT_APP;
9965            }
9966            if (pkgSetting.getVirtulalPreload(userId)) {
9967                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9968            }
9969        }
9970
9971        // Scan as privileged apps that share a user with a priv-app.
9972        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9973                && (pkg.mSharedUserId != null)) {
9974            SharedUserSetting sharedUserSetting = null;
9975            try {
9976                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9977            } catch (PackageManagerException ignore) {}
9978            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9979                // Exempt SharedUsers signed with the platform key.
9980                // TODO(b/72378145) Fix this exemption. Force signature apps
9981                // to whitelist their privileged permissions just like other
9982                // priv-apps.
9983                synchronized (mPackages) {
9984                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9985                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9986                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9987                        scanFlags |= SCAN_AS_PRIVILEGED;
9988                    }
9989                }
9990            }
9991        }
9992
9993        return scanFlags;
9994    }
9995
9996    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
9997    // the results / removing app data needs to be moved up a level to the callers of this
9998    // method. Also, we need to solve the problem of potentially creating a new shared user
9999    // setting. That can probably be done later and patch things up after the fact.
10000    @GuardedBy("mInstallLock")
10001    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
10002            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10003            @Nullable UserHandle user) throws PackageManagerException {
10004
10005        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10006        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10007        if (realPkgName != null) {
10008            ensurePackageRenamed(pkg, renamedPkgName);
10009        }
10010        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10011        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10012        final PackageSetting disabledPkgSetting =
10013                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10014
10015        if (mTransferedPackages.contains(pkg.packageName)) {
10016            Slog.w(TAG, "Package " + pkg.packageName
10017                    + " was transferred to another, but its .apk remains");
10018        }
10019
10020        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10021        synchronized (mPackages) {
10022            applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10023            assertPackageIsValid(pkg, parseFlags, scanFlags);
10024
10025            SharedUserSetting sharedUserSetting = null;
10026            if (pkg.mSharedUserId != null) {
10027                // SIDE EFFECTS; may potentially allocate a new shared user
10028                sharedUserSetting = mSettings.getSharedUserLPw(
10029                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10030                if (DEBUG_PACKAGE_SCANNING) {
10031                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10032                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10033                                + " (uid=" + sharedUserSetting.userId + "):"
10034                                + " packages=" + sharedUserSetting.packages);
10035                }
10036            }
10037
10038            boolean scanSucceeded = false;
10039            try {
10040                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10041                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10042                        (pkg == mPlatformPackage), user);
10043                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10044                if (result.success) {
10045                    commitScanResultsLocked(request, result);
10046                }
10047                scanSucceeded = true;
10048            } finally {
10049                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10050                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10051                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10052                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10053                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10054                  }
10055            }
10056        }
10057        return pkg;
10058    }
10059
10060    /**
10061     * Commits the package scan and modifies system state.
10062     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10063     * of committing the package, leaving the system in an inconsistent state.
10064     * This needs to be fixed so, once we get to this point, no errors are
10065     * possible and the system is not left in an inconsistent state.
10066     */
10067    @GuardedBy("mPackages")
10068    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10069            throws PackageManagerException {
10070        final PackageParser.Package pkg = request.pkg;
10071        final @ParseFlags int parseFlags = request.parseFlags;
10072        final @ScanFlags int scanFlags = request.scanFlags;
10073        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10074        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10075        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10076        final UserHandle user = request.user;
10077        final String realPkgName = request.realPkgName;
10078        final PackageSetting pkgSetting = result.pkgSetting;
10079        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10080        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10081
10082        if (newPkgSettingCreated) {
10083            if (originalPkgSetting != null) {
10084                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10085            }
10086            // THROWS: when we can't allocate a user id. add call to check if there's
10087            // enough space to ensure we won't throw; otherwise, don't modify state
10088            mSettings.addUserToSettingLPw(pkgSetting);
10089
10090            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10091                mTransferedPackages.add(originalPkgSetting.name);
10092            }
10093        }
10094        // TODO(toddke): Consider a method specifically for modifying the Package object
10095        // post scan; or, moving this stuff out of the Package object since it has nothing
10096        // to do with the package on disk.
10097        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10098        // for creating the application ID. If we did this earlier, we would be saving the
10099        // correct ID.
10100        pkg.applicationInfo.uid = pkgSetting.appId;
10101
10102        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10103
10104        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10105            mTransferedPackages.add(pkg.packageName);
10106        }
10107
10108        // THROWS: when requested libraries that can't be found. it only changes
10109        // the state of the passed in pkg object, so, move to the top of the method
10110        // and allow it to abort
10111        if ((scanFlags & SCAN_BOOTING) == 0
10112                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10113            // Check all shared libraries and map to their actual file path.
10114            // We only do this here for apps not on a system dir, because those
10115            // are the only ones that can fail an install due to this.  We
10116            // will take care of the system apps by updating all of their
10117            // library paths after the scan is done. Also during the initial
10118            // scan don't update any libs as we do this wholesale after all
10119            // apps are scanned to avoid dependency based scanning.
10120            updateSharedLibrariesLPr(pkg, null);
10121        }
10122
10123        // All versions of a static shared library are referenced with the same
10124        // package name. Internally, we use a synthetic package name to allow
10125        // multiple versions of the same shared library to be installed. So,
10126        // we need to generate the synthetic package name of the latest shared
10127        // library in order to compare signatures.
10128        PackageSetting signatureCheckPs = pkgSetting;
10129        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10130            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10131            if (libraryEntry != null) {
10132                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10133            }
10134        }
10135
10136        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10137        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10138            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10139                // We just determined the app is signed correctly, so bring
10140                // over the latest parsed certs.
10141                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10142            } else {
10143                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10144                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10145                            "Package " + pkg.packageName + " upgrade keys do not match the "
10146                                    + "previously installed version");
10147                } else {
10148                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10149                    String msg = "System package " + pkg.packageName
10150                            + " signature changed; retaining data.";
10151                    reportSettingsProblem(Log.WARN, msg);
10152                }
10153            }
10154        } else {
10155            try {
10156                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10157                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10158                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10159                        pkg.mSigningDetails, compareCompat, compareRecover);
10160                // The new KeySets will be re-added later in the scanning process.
10161                if (compatMatch) {
10162                    synchronized (mPackages) {
10163                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10164                    }
10165                }
10166                // We just determined the app is signed correctly, so bring
10167                // over the latest parsed certs.
10168                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10169
10170
10171                // if this is is a sharedUser, check to see if the new package is signed by a newer
10172                // signing certificate than the existing one, and if so, copy over the new details
10173                if (signatureCheckPs.sharedUser != null
10174                        && pkg.mSigningDetails.hasAncestor(
10175                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10176                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10177                }
10178            } catch (PackageManagerException e) {
10179                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10180                    throw e;
10181                }
10182                // The signature has changed, but this package is in the system
10183                // image...  let's recover!
10184                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10185                // However...  if this package is part of a shared user, but it
10186                // doesn't match the signature of the shared user, let's fail.
10187                // What this means is that you can't change the signatures
10188                // associated with an overall shared user, which doesn't seem all
10189                // that unreasonable.
10190                if (signatureCheckPs.sharedUser != null) {
10191                    if (compareSignatures(
10192                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10193                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10194                        throw new PackageManagerException(
10195                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10196                                "Signature mismatch for shared user: "
10197                                        + pkgSetting.sharedUser);
10198                    }
10199                }
10200                // File a report about this.
10201                String msg = "System package " + pkg.packageName
10202                        + " signature changed; retaining data.";
10203                reportSettingsProblem(Log.WARN, msg);
10204            } catch (IllegalArgumentException e) {
10205
10206                // should never happen: certs matched when checking, but not when comparing
10207                // old to new for sharedUser
10208                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10209                        "Signing certificates comparison made on incomparable signing details"
10210                        + " but somehow passed verifySignatures!");
10211            }
10212        }
10213
10214        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10215            // This package wants to adopt ownership of permissions from
10216            // another package.
10217            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10218                final String origName = pkg.mAdoptPermissions.get(i);
10219                final PackageSetting orig = mSettings.getPackageLPr(origName);
10220                if (orig != null) {
10221                    if (verifyPackageUpdateLPr(orig, pkg)) {
10222                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10223                                + pkg.packageName);
10224                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10225                    }
10226                }
10227            }
10228        }
10229
10230        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10231            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10232                final String codePathString = changedAbiCodePath.get(i);
10233                try {
10234                    mInstaller.rmdex(codePathString,
10235                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10236                } catch (InstallerException ignored) {
10237                }
10238            }
10239        }
10240
10241        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10242            if (oldPkgSetting != null) {
10243                synchronized (mPackages) {
10244                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10245                }
10246            }
10247        } else {
10248            final int userId = user == null ? 0 : user.getIdentifier();
10249            // Modify state for the given package setting
10250            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10251                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10252            if (pkgSetting.getInstantApp(userId)) {
10253                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10254            }
10255        }
10256    }
10257
10258    /**
10259     * Returns the "real" name of the package.
10260     * <p>This may differ from the package's actual name if the application has already
10261     * been installed under one of this package's original names.
10262     */
10263    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10264            @Nullable String renamedPkgName) {
10265        if (isPackageRenamed(pkg, renamedPkgName)) {
10266            return pkg.mRealPackage;
10267        }
10268        return null;
10269    }
10270
10271    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10272    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10273            @Nullable String renamedPkgName) {
10274        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10275    }
10276
10277    /**
10278     * Returns the original package setting.
10279     * <p>A package can migrate its name during an update. In this scenario, a package
10280     * designates a set of names that it considers as one of its original names.
10281     * <p>An original package must be signed identically and it must have the same
10282     * shared user [if any].
10283     */
10284    @GuardedBy("mPackages")
10285    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10286            @Nullable String renamedPkgName) {
10287        if (!isPackageRenamed(pkg, renamedPkgName)) {
10288            return null;
10289        }
10290        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10291            final PackageSetting originalPs =
10292                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10293            if (originalPs != null) {
10294                // the package is already installed under its original name...
10295                // but, should we use it?
10296                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10297                    // the new package is incompatible with the original
10298                    continue;
10299                } else if (originalPs.sharedUser != null) {
10300                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10301                        // the shared user id is incompatible with the original
10302                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10303                                + " to " + pkg.packageName + ": old uid "
10304                                + originalPs.sharedUser.name
10305                                + " differs from " + pkg.mSharedUserId);
10306                        continue;
10307                    }
10308                    // TODO: Add case when shared user id is added [b/28144775]
10309                } else {
10310                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10311                            + pkg.packageName + " to old name " + originalPs.name);
10312                }
10313                return originalPs;
10314            }
10315        }
10316        return null;
10317    }
10318
10319    /**
10320     * Renames the package if it was installed under a different name.
10321     * <p>When we've already installed the package under an original name, update
10322     * the new package so we can continue to have the old name.
10323     */
10324    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10325            @NonNull String renamedPackageName) {
10326        if (pkg.mOriginalPackages == null
10327                || !pkg.mOriginalPackages.contains(renamedPackageName)
10328                || pkg.packageName.equals(renamedPackageName)) {
10329            return;
10330        }
10331        pkg.setPackageName(renamedPackageName);
10332    }
10333
10334    /**
10335     * Just scans the package without any side effects.
10336     * <p>Not entirely true at the moment. There is still one side effect -- this
10337     * method potentially modifies a live {@link PackageSetting} object representing
10338     * the package being scanned. This will be resolved in the future.
10339     *
10340     * @param request Information about the package to be scanned
10341     * @param isUnderFactoryTest Whether or not the device is under factory test
10342     * @param currentTime The current time, in millis
10343     * @return The results of the scan
10344     */
10345    @GuardedBy("mInstallLock")
10346    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10347            boolean isUnderFactoryTest, long currentTime)
10348                    throws PackageManagerException {
10349        final PackageParser.Package pkg = request.pkg;
10350        PackageSetting pkgSetting = request.pkgSetting;
10351        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10352        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10353        final @ParseFlags int parseFlags = request.parseFlags;
10354        final @ScanFlags int scanFlags = request.scanFlags;
10355        final String realPkgName = request.realPkgName;
10356        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10357        final UserHandle user = request.user;
10358        final boolean isPlatformPackage = request.isPlatformPackage;
10359
10360        List<String> changedAbiCodePath = null;
10361
10362        if (DEBUG_PACKAGE_SCANNING) {
10363            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10364                Log.d(TAG, "Scanning package " + pkg.packageName);
10365        }
10366
10367        if (Build.IS_DEBUGGABLE &&
10368                pkg.isPrivileged() &&
10369                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10370            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10371        }
10372
10373        // Initialize package source and resource directories
10374        final File scanFile = new File(pkg.codePath);
10375        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10376        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10377
10378        // We keep references to the derived CPU Abis from settings in oder to reuse
10379        // them in the case where we're not upgrading or booting for the first time.
10380        String primaryCpuAbiFromSettings = null;
10381        String secondaryCpuAbiFromSettings = null;
10382        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10383
10384        if (!needToDeriveAbi) {
10385            if (pkgSetting != null) {
10386                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10387                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10388            } else {
10389                // Re-scanning a system package after uninstalling updates; need to derive ABI
10390                needToDeriveAbi = true;
10391            }
10392        }
10393
10394        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10395            PackageManagerService.reportSettingsProblem(Log.WARN,
10396                    "Package " + pkg.packageName + " shared user changed from "
10397                            + (pkgSetting.sharedUser != null
10398                            ? pkgSetting.sharedUser.name : "<nothing>")
10399                            + " to "
10400                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10401                            + "; replacing with new");
10402            pkgSetting = null;
10403        }
10404
10405        String[] usesStaticLibraries = null;
10406        if (pkg.usesStaticLibraries != null) {
10407            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10408            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10409        }
10410        final boolean createNewPackage = (pkgSetting == null);
10411        if (createNewPackage) {
10412            final String parentPackageName = (pkg.parentPackage != null)
10413                    ? pkg.parentPackage.packageName : null;
10414            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10415            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10416            // REMOVE SharedUserSetting from method; update in a separate call
10417            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10418                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10419                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10420                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10421                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10422                    user, true /*allowInstall*/, instantApp, virtualPreload,
10423                    parentPackageName, pkg.getChildPackageNames(),
10424                    UserManagerService.getInstance(), usesStaticLibraries,
10425                    pkg.usesStaticLibrariesVersions);
10426        } else {
10427            // REMOVE SharedUserSetting from method; update in a separate call.
10428            //
10429            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10430            // secondaryCpuAbi are not known at this point so we always update them
10431            // to null here, only to reset them at a later point.
10432            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10433                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10434                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10435                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10436                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10437                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10438        }
10439        if (createNewPackage && originalPkgSetting != null) {
10440            // This is the initial transition from the original package, so,
10441            // fix up the new package's name now. We must do this after looking
10442            // up the package under its new name, so getPackageLP takes care of
10443            // fiddling things correctly.
10444            pkg.setPackageName(originalPkgSetting.name);
10445
10446            // File a report about this.
10447            String msg = "New package " + pkgSetting.realName
10448                    + " renamed to replace old package " + pkgSetting.name;
10449            reportSettingsProblem(Log.WARN, msg);
10450        }
10451
10452        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10453        // for existing packages, change the install state; but, only if it's explicitly specified
10454        if (!createNewPackage) {
10455            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10456            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10457            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10458        }
10459
10460        if (disabledPkgSetting != null) {
10461            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10462        }
10463
10464        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10465        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10466        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10467        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10468        // least restrictive selinux domain.
10469        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10470        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10471        // ensures that all packages continue to run in the same selinux domain.
10472        final int targetSdkVersion =
10473            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10474            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10475        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10476        // They currently can be if the sharedUser apps are signed with the platform key.
10477        final boolean isPrivileged = (sharedUserSetting != null) ?
10478            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10479
10480        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10481                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10482        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10483                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10484
10485        pkg.mExtras = pkgSetting;
10486        pkg.applicationInfo.processName = fixProcessName(
10487                pkg.applicationInfo.packageName,
10488                pkg.applicationInfo.processName);
10489
10490        if (!isPlatformPackage) {
10491            // Get all of our default paths setup
10492            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10493        }
10494
10495        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10496
10497        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10498            if (needToDeriveAbi) {
10499                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10500                final boolean extractNativeLibs = !pkg.isLibrary();
10501                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10502                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10503
10504                // Some system apps still use directory structure for native libraries
10505                // in which case we might end up not detecting abi solely based on apk
10506                // structure. Try to detect abi based on directory structure.
10507                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10508                        pkg.applicationInfo.primaryCpuAbi == null) {
10509                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10510                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10511                }
10512            } else {
10513                // This is not a first boot or an upgrade, don't bother deriving the
10514                // ABI during the scan. Instead, trust the value that was stored in the
10515                // package setting.
10516                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10517                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10518
10519                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10520
10521                if (DEBUG_ABI_SELECTION) {
10522                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10523                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10524                            pkg.applicationInfo.secondaryCpuAbi);
10525                }
10526            }
10527        } else {
10528            if ((scanFlags & SCAN_MOVE) != 0) {
10529                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10530                // but we already have this packages package info in the PackageSetting. We just
10531                // use that and derive the native library path based on the new codepath.
10532                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10533                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10534            }
10535
10536            // Set native library paths again. For moves, the path will be updated based on the
10537            // ABIs we've determined above. For non-moves, the path will be updated based on the
10538            // ABIs we determined during compilation, but the path will depend on the final
10539            // package path (after the rename away from the stage path).
10540            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10541        }
10542
10543        // This is a special case for the "system" package, where the ABI is
10544        // dictated by the zygote configuration (and init.rc). We should keep track
10545        // of this ABI so that we can deal with "normal" applications that run under
10546        // the same UID correctly.
10547        if (isPlatformPackage) {
10548            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10549                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10550        }
10551
10552        // If there's a mismatch between the abi-override in the package setting
10553        // and the abiOverride specified for the install. Warn about this because we
10554        // would've already compiled the app without taking the package setting into
10555        // account.
10556        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10557            if (cpuAbiOverride == null && pkg.packageName != null) {
10558                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10559                        " for package " + pkg.packageName);
10560            }
10561        }
10562
10563        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10564        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10565        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10566
10567        // Copy the derived override back to the parsed package, so that we can
10568        // update the package settings accordingly.
10569        pkg.cpuAbiOverride = cpuAbiOverride;
10570
10571        if (DEBUG_ABI_SELECTION) {
10572            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10573                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10574                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10575        }
10576
10577        // Push the derived path down into PackageSettings so we know what to
10578        // clean up at uninstall time.
10579        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10580
10581        if (DEBUG_ABI_SELECTION) {
10582            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10583                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10584                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10585        }
10586
10587        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10588            // We don't do this here during boot because we can do it all
10589            // at once after scanning all existing packages.
10590            //
10591            // We also do this *before* we perform dexopt on this package, so that
10592            // we can avoid redundant dexopts, and also to make sure we've got the
10593            // code and package path correct.
10594            changedAbiCodePath =
10595                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10596        }
10597
10598        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10599                android.Manifest.permission.FACTORY_TEST)) {
10600            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10601        }
10602
10603        if (isSystemApp(pkg)) {
10604            pkgSetting.isOrphaned = true;
10605        }
10606
10607        // Take care of first install / last update times.
10608        final long scanFileTime = getLastModifiedTime(pkg);
10609        if (currentTime != 0) {
10610            if (pkgSetting.firstInstallTime == 0) {
10611                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10612            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10613                pkgSetting.lastUpdateTime = currentTime;
10614            }
10615        } else if (pkgSetting.firstInstallTime == 0) {
10616            // We need *something*.  Take time time stamp of the file.
10617            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10618        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10619            if (scanFileTime != pkgSetting.timeStamp) {
10620                // A package on the system image has changed; consider this
10621                // to be an update.
10622                pkgSetting.lastUpdateTime = scanFileTime;
10623            }
10624        }
10625        pkgSetting.setTimeStamp(scanFileTime);
10626
10627        pkgSetting.pkg = pkg;
10628        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10629        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10630            pkgSetting.versionCode = pkg.getLongVersionCode();
10631        }
10632        // Update volume if needed
10633        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10634        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10635            Slog.i(PackageManagerService.TAG,
10636                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10637                    + " package " + pkg.packageName
10638                    + " volume from " + pkgSetting.volumeUuid
10639                    + " to " + volumeUuid);
10640            pkgSetting.volumeUuid = volumeUuid;
10641        }
10642
10643        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10644    }
10645
10646    /**
10647     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10648     */
10649    private static boolean apkHasCode(String fileName) {
10650        StrictJarFile jarFile = null;
10651        try {
10652            jarFile = new StrictJarFile(fileName,
10653                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10654            return jarFile.findEntry("classes.dex") != null;
10655        } catch (IOException ignore) {
10656        } finally {
10657            try {
10658                if (jarFile != null) {
10659                    jarFile.close();
10660                }
10661            } catch (IOException ignore) {}
10662        }
10663        return false;
10664    }
10665
10666    /**
10667     * Enforces code policy for the package. This ensures that if an APK has
10668     * declared hasCode="true" in its manifest that the APK actually contains
10669     * code.
10670     *
10671     * @throws PackageManagerException If bytecode could not be found when it should exist
10672     */
10673    private static void assertCodePolicy(PackageParser.Package pkg)
10674            throws PackageManagerException {
10675        final boolean shouldHaveCode =
10676                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10677        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10678            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10679                    "Package " + pkg.baseCodePath + " code is missing");
10680        }
10681
10682        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10683            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10684                final boolean splitShouldHaveCode =
10685                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10686                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10687                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10688                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10689                }
10690            }
10691        }
10692    }
10693
10694    /**
10695     * Applies policy to the parsed package based upon the given policy flags.
10696     * Ensures the package is in a good state.
10697     * <p>
10698     * Implementation detail: This method must NOT have any side effect. It would
10699     * ideally be static, but, it requires locks to read system state.
10700     */
10701    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10702            final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
10703        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10704            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10705            if (pkg.applicationInfo.isDirectBootAware()) {
10706                // we're direct boot aware; set for all components
10707                for (PackageParser.Service s : pkg.services) {
10708                    s.info.encryptionAware = s.info.directBootAware = true;
10709                }
10710                for (PackageParser.Provider p : pkg.providers) {
10711                    p.info.encryptionAware = p.info.directBootAware = true;
10712                }
10713                for (PackageParser.Activity a : pkg.activities) {
10714                    a.info.encryptionAware = a.info.directBootAware = true;
10715                }
10716                for (PackageParser.Activity r : pkg.receivers) {
10717                    r.info.encryptionAware = r.info.directBootAware = true;
10718                }
10719            }
10720            if (compressedFileExists(pkg.codePath)) {
10721                pkg.isStub = true;
10722            }
10723        } else {
10724            // non system apps can't be flagged as core
10725            pkg.coreApp = false;
10726            // clear flags not applicable to regular apps
10727            pkg.applicationInfo.flags &=
10728                    ~ApplicationInfo.FLAG_PERSISTENT;
10729            pkg.applicationInfo.privateFlags &=
10730                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10731            pkg.applicationInfo.privateFlags &=
10732                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10733            // cap permission priorities
10734            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10735                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10736                    pkg.permissionGroups.get(i).info.priority = 0;
10737                }
10738            }
10739        }
10740        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10741            // clear protected broadcasts
10742            pkg.protectedBroadcasts = null;
10743            // ignore export request for single user receivers
10744            if (pkg.receivers != null) {
10745                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10746                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10747                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10748                        receiver.info.exported = false;
10749                    }
10750                }
10751            }
10752            // ignore export request for single user services
10753            if (pkg.services != null) {
10754                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10755                    final PackageParser.Service service = pkg.services.get(i);
10756                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10757                        service.info.exported = false;
10758                    }
10759                }
10760            }
10761            // ignore export request for single user providers
10762            if (pkg.providers != null) {
10763                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10764                    final PackageParser.Provider provider = pkg.providers.get(i);
10765                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10766                        provider.info.exported = false;
10767                    }
10768                }
10769            }
10770        }
10771
10772        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10773            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10774        }
10775
10776        if ((scanFlags & SCAN_AS_OEM) != 0) {
10777            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10778        }
10779
10780        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10781            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10782        }
10783
10784        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10785            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10786        }
10787
10788        // Check if the package is signed with the same key as the platform package.
10789        if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
10790                (platformPkg != null && compareSignatures(
10791                        platformPkg.mSigningDetails.signatures,
10792                        pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
10793            pkg.applicationInfo.privateFlags |=
10794                ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
10795        }
10796
10797        if (!isSystemApp(pkg)) {
10798            // Only system apps can use these features.
10799            pkg.mOriginalPackages = null;
10800            pkg.mRealPackage = null;
10801            pkg.mAdoptPermissions = null;
10802        }
10803    }
10804
10805    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10806            throws PackageManagerException {
10807        if (object == null) {
10808            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10809        }
10810        return object;
10811    }
10812
10813    /**
10814     * Asserts the parsed package is valid according to the given policy. If the
10815     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10816     * <p>
10817     * Implementation detail: This method must NOT have any side effects. It would
10818     * ideally be static, but, it requires locks to read system state.
10819     *
10820     * @throws PackageManagerException If the package fails any of the validation checks
10821     */
10822    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10823            final @ScanFlags int scanFlags)
10824                    throws PackageManagerException {
10825        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10826            assertCodePolicy(pkg);
10827        }
10828
10829        if (pkg.applicationInfo.getCodePath() == null ||
10830                pkg.applicationInfo.getResourcePath() == null) {
10831            // Bail out. The resource and code paths haven't been set.
10832            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10833                    "Code and resource paths haven't been set correctly");
10834        }
10835
10836        // Make sure we're not adding any bogus keyset info
10837        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10838        ksms.assertScannedPackageValid(pkg);
10839
10840        synchronized (mPackages) {
10841            // The special "android" package can only be defined once
10842            if (pkg.packageName.equals("android")) {
10843                if (mAndroidApplication != null) {
10844                    Slog.w(TAG, "*************************************************");
10845                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10846                    Slog.w(TAG, " codePath=" + pkg.codePath);
10847                    Slog.w(TAG, "*************************************************");
10848                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10849                            "Core android package being redefined.  Skipping.");
10850                }
10851            }
10852
10853            // A package name must be unique; don't allow duplicates
10854            if (mPackages.containsKey(pkg.packageName)) {
10855                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10856                        "Application package " + pkg.packageName
10857                        + " already installed.  Skipping duplicate.");
10858            }
10859
10860            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10861                // Static libs have a synthetic package name containing the version
10862                // but we still want the base name to be unique.
10863                if (mPackages.containsKey(pkg.manifestPackageName)) {
10864                    throw new PackageManagerException(
10865                            "Duplicate static shared lib provider package");
10866                }
10867
10868                // Static shared libraries should have at least O target SDK
10869                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10870                    throw new PackageManagerException(
10871                            "Packages declaring static-shared libs must target O SDK or higher");
10872                }
10873
10874                // Package declaring static a shared lib cannot be instant apps
10875                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10876                    throw new PackageManagerException(
10877                            "Packages declaring static-shared libs cannot be instant apps");
10878                }
10879
10880                // Package declaring static a shared lib cannot be renamed since the package
10881                // name is synthetic and apps can't code around package manager internals.
10882                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10883                    throw new PackageManagerException(
10884                            "Packages declaring static-shared libs cannot be renamed");
10885                }
10886
10887                // Package declaring static a shared lib cannot declare child packages
10888                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10889                    throw new PackageManagerException(
10890                            "Packages declaring static-shared libs cannot have child packages");
10891                }
10892
10893                // Package declaring static a shared lib cannot declare dynamic libs
10894                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10895                    throw new PackageManagerException(
10896                            "Packages declaring static-shared libs cannot declare dynamic libs");
10897                }
10898
10899                // Package declaring static a shared lib cannot declare shared users
10900                if (pkg.mSharedUserId != null) {
10901                    throw new PackageManagerException(
10902                            "Packages declaring static-shared libs cannot declare shared users");
10903                }
10904
10905                // Static shared libs cannot declare activities
10906                if (!pkg.activities.isEmpty()) {
10907                    throw new PackageManagerException(
10908                            "Static shared libs cannot declare activities");
10909                }
10910
10911                // Static shared libs cannot declare services
10912                if (!pkg.services.isEmpty()) {
10913                    throw new PackageManagerException(
10914                            "Static shared libs cannot declare services");
10915                }
10916
10917                // Static shared libs cannot declare providers
10918                if (!pkg.providers.isEmpty()) {
10919                    throw new PackageManagerException(
10920                            "Static shared libs cannot declare content providers");
10921                }
10922
10923                // Static shared libs cannot declare receivers
10924                if (!pkg.receivers.isEmpty()) {
10925                    throw new PackageManagerException(
10926                            "Static shared libs cannot declare broadcast receivers");
10927                }
10928
10929                // Static shared libs cannot declare permission groups
10930                if (!pkg.permissionGroups.isEmpty()) {
10931                    throw new PackageManagerException(
10932                            "Static shared libs cannot declare permission groups");
10933                }
10934
10935                // Static shared libs cannot declare permissions
10936                if (!pkg.permissions.isEmpty()) {
10937                    throw new PackageManagerException(
10938                            "Static shared libs cannot declare permissions");
10939                }
10940
10941                // Static shared libs cannot declare protected broadcasts
10942                if (pkg.protectedBroadcasts != null) {
10943                    throw new PackageManagerException(
10944                            "Static shared libs cannot declare protected broadcasts");
10945                }
10946
10947                // Static shared libs cannot be overlay targets
10948                if (pkg.mOverlayTarget != null) {
10949                    throw new PackageManagerException(
10950                            "Static shared libs cannot be overlay targets");
10951                }
10952
10953                // The version codes must be ordered as lib versions
10954                long minVersionCode = Long.MIN_VALUE;
10955                long maxVersionCode = Long.MAX_VALUE;
10956
10957                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10958                        pkg.staticSharedLibName);
10959                if (versionedLib != null) {
10960                    final int versionCount = versionedLib.size();
10961                    for (int i = 0; i < versionCount; i++) {
10962                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10963                        final long libVersionCode = libInfo.getDeclaringPackage()
10964                                .getLongVersionCode();
10965                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10966                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10967                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10968                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10969                        } else {
10970                            minVersionCode = maxVersionCode = libVersionCode;
10971                            break;
10972                        }
10973                    }
10974                }
10975                if (pkg.getLongVersionCode() < minVersionCode
10976                        || pkg.getLongVersionCode() > maxVersionCode) {
10977                    throw new PackageManagerException("Static shared"
10978                            + " lib version codes must be ordered as lib versions");
10979                }
10980            }
10981
10982            // Only privileged apps and updated privileged apps can add child packages.
10983            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10984                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10985                    throw new PackageManagerException("Only privileged apps can add child "
10986                            + "packages. Ignoring package " + pkg.packageName);
10987                }
10988                final int childCount = pkg.childPackages.size();
10989                for (int i = 0; i < childCount; i++) {
10990                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10991                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10992                            childPkg.packageName)) {
10993                        throw new PackageManagerException("Can't override child of "
10994                                + "another disabled app. Ignoring package " + pkg.packageName);
10995                    }
10996                }
10997            }
10998
10999            // If we're only installing presumed-existing packages, require that the
11000            // scanned APK is both already known and at the path previously established
11001            // for it.  Previously unknown packages we pick up normally, but if we have an
11002            // a priori expectation about this package's install presence, enforce it.
11003            // With a singular exception for new system packages. When an OTA contains
11004            // a new system package, we allow the codepath to change from a system location
11005            // to the user-installed location. If we don't allow this change, any newer,
11006            // user-installed version of the application will be ignored.
11007            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11008                if (mExpectingBetter.containsKey(pkg.packageName)) {
11009                    logCriticalInfo(Log.WARN,
11010                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11011                } else {
11012                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11013                    if (known != null) {
11014                        if (DEBUG_PACKAGE_SCANNING) {
11015                            Log.d(TAG, "Examining " + pkg.codePath
11016                                    + " and requiring known paths " + known.codePathString
11017                                    + " & " + known.resourcePathString);
11018                        }
11019                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11020                                || !pkg.applicationInfo.getResourcePath().equals(
11021                                        known.resourcePathString)) {
11022                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11023                                    "Application package " + pkg.packageName
11024                                    + " found at " + pkg.applicationInfo.getCodePath()
11025                                    + " but expected at " + known.codePathString
11026                                    + "; ignoring.");
11027                        }
11028                    } else {
11029                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11030                                "Application package " + pkg.packageName
11031                                + " not found; ignoring.");
11032                    }
11033                }
11034            }
11035
11036            // Verify that this new package doesn't have any content providers
11037            // that conflict with existing packages.  Only do this if the
11038            // package isn't already installed, since we don't want to break
11039            // things that are installed.
11040            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11041                final int N = pkg.providers.size();
11042                int i;
11043                for (i=0; i<N; i++) {
11044                    PackageParser.Provider p = pkg.providers.get(i);
11045                    if (p.info.authority != null) {
11046                        String names[] = p.info.authority.split(";");
11047                        for (int j = 0; j < names.length; j++) {
11048                            if (mProvidersByAuthority.containsKey(names[j])) {
11049                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11050                                final String otherPackageName =
11051                                        ((other != null && other.getComponentName() != null) ?
11052                                                other.getComponentName().getPackageName() : "?");
11053                                throw new PackageManagerException(
11054                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11055                                        "Can't install because provider name " + names[j]
11056                                                + " (in package " + pkg.applicationInfo.packageName
11057                                                + ") is already used by " + otherPackageName);
11058                            }
11059                        }
11060                    }
11061                }
11062            }
11063
11064            // Verify that packages sharing a user with a privileged app are marked as privileged.
11065            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11066                SharedUserSetting sharedUserSetting = null;
11067                try {
11068                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11069                } catch (PackageManagerException ignore) {}
11070                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11071                    // Exempt SharedUsers signed with the platform key.
11072                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11073                    if ((platformPkgSetting.signatures.mSigningDetails
11074                            != PackageParser.SigningDetails.UNKNOWN)
11075                            && (compareSignatures(
11076                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11077                                    pkg.mSigningDetails.signatures)
11078                                            != PackageManager.SIGNATURE_MATCH)) {
11079                        throw new PackageManagerException("Apps that share a user with a " +
11080                                "privileged app must themselves be marked as privileged. " +
11081                                pkg.packageName + " shares privileged user " +
11082                                pkg.mSharedUserId + ".");
11083                    }
11084                }
11085            }
11086
11087            // Apply policies specific for runtime resource overlays (RROs).
11088            if (pkg.mOverlayTarget != null) {
11089                // System overlays have some restrictions on their use of the 'static' state.
11090                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11091                    // We are scanning a system overlay. This can be the first scan of the
11092                    // system/vendor/oem partition, or an update to the system overlay.
11093                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11094                        // This must be an update to a system overlay.
11095                        final PackageSetting previousPkg = assertNotNull(
11096                                mSettings.getPackageLPr(pkg.packageName),
11097                                "previous package state not present");
11098
11099                        // Static overlays cannot be updated.
11100                        if (previousPkg.pkg.mOverlayIsStatic) {
11101                            throw new PackageManagerException("Overlay " + pkg.packageName +
11102                                    " is static and cannot be upgraded.");
11103                        // Non-static overlays cannot be converted to static overlays.
11104                        } else if (pkg.mOverlayIsStatic) {
11105                            throw new PackageManagerException("Overlay " + pkg.packageName +
11106                                    " cannot be upgraded into a static overlay.");
11107                        }
11108                    }
11109                } else {
11110                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11111                    if (pkg.mOverlayIsStatic) {
11112                        throw new PackageManagerException("Overlay " + pkg.packageName +
11113                                " is static but not pre-installed.");
11114                    }
11115
11116                    // The only case where we allow installation of a non-system overlay is when
11117                    // its signature is signed with the platform certificate.
11118                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11119                    if ((platformPkgSetting.signatures.mSigningDetails
11120                            != PackageParser.SigningDetails.UNKNOWN)
11121                            && (compareSignatures(
11122                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11123                                    pkg.mSigningDetails.signatures)
11124                                            != PackageManager.SIGNATURE_MATCH)) {
11125                        throw new PackageManagerException("Overlay " + pkg.packageName +
11126                                " must be signed with the platform certificate.");
11127                    }
11128                }
11129            }
11130        }
11131    }
11132
11133    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11134            int type, String declaringPackageName, long declaringVersionCode) {
11135        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11136        if (versionedLib == null) {
11137            versionedLib = new LongSparseArray<>();
11138            mSharedLibraries.put(name, versionedLib);
11139            if (type == SharedLibraryInfo.TYPE_STATIC) {
11140                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11141            }
11142        } else if (versionedLib.indexOfKey(version) >= 0) {
11143            return false;
11144        }
11145        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11146                version, type, declaringPackageName, declaringVersionCode);
11147        versionedLib.put(version, libEntry);
11148        return true;
11149    }
11150
11151    private boolean removeSharedLibraryLPw(String name, long version) {
11152        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11153        if (versionedLib == null) {
11154            return false;
11155        }
11156        final int libIdx = versionedLib.indexOfKey(version);
11157        if (libIdx < 0) {
11158            return false;
11159        }
11160        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11161        versionedLib.remove(version);
11162        if (versionedLib.size() <= 0) {
11163            mSharedLibraries.remove(name);
11164            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11165                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11166                        .getPackageName());
11167            }
11168        }
11169        return true;
11170    }
11171
11172    /**
11173     * Adds a scanned package to the system. When this method is finished, the package will
11174     * be available for query, resolution, etc...
11175     */
11176    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11177            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11178        final String pkgName = pkg.packageName;
11179        if (mCustomResolverComponentName != null &&
11180                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11181            setUpCustomResolverActivity(pkg);
11182        }
11183
11184        if (pkg.packageName.equals("android")) {
11185            synchronized (mPackages) {
11186                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11187                    // Set up information for our fall-back user intent resolution activity.
11188                    mPlatformPackage = pkg;
11189                    pkg.mVersionCode = mSdkVersion;
11190                    pkg.mVersionCodeMajor = 0;
11191                    mAndroidApplication = pkg.applicationInfo;
11192                    if (!mResolverReplaced) {
11193                        mResolveActivity.applicationInfo = mAndroidApplication;
11194                        mResolveActivity.name = ResolverActivity.class.getName();
11195                        mResolveActivity.packageName = mAndroidApplication.packageName;
11196                        mResolveActivity.processName = "system:ui";
11197                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11198                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11199                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11200                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11201                        mResolveActivity.exported = true;
11202                        mResolveActivity.enabled = true;
11203                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11204                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11205                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11206                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11207                                | ActivityInfo.CONFIG_ORIENTATION
11208                                | ActivityInfo.CONFIG_KEYBOARD
11209                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11210                        mResolveInfo.activityInfo = mResolveActivity;
11211                        mResolveInfo.priority = 0;
11212                        mResolveInfo.preferredOrder = 0;
11213                        mResolveInfo.match = 0;
11214                        mResolveComponentName = new ComponentName(
11215                                mAndroidApplication.packageName, mResolveActivity.name);
11216                    }
11217                }
11218            }
11219        }
11220
11221        ArrayList<PackageParser.Package> clientLibPkgs = null;
11222        // writer
11223        synchronized (mPackages) {
11224            boolean hasStaticSharedLibs = false;
11225
11226            // Any app can add new static shared libraries
11227            if (pkg.staticSharedLibName != null) {
11228                // Static shared libs don't allow renaming as they have synthetic package
11229                // names to allow install of multiple versions, so use name from manifest.
11230                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11231                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11232                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11233                    hasStaticSharedLibs = true;
11234                } else {
11235                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11236                                + pkg.staticSharedLibName + " already exists; skipping");
11237                }
11238                // Static shared libs cannot be updated once installed since they
11239                // use synthetic package name which includes the version code, so
11240                // not need to update other packages's shared lib dependencies.
11241            }
11242
11243            if (!hasStaticSharedLibs
11244                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11245                // Only system apps can add new dynamic shared libraries.
11246                if (pkg.libraryNames != null) {
11247                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11248                        String name = pkg.libraryNames.get(i);
11249                        boolean allowed = false;
11250                        if (pkg.isUpdatedSystemApp()) {
11251                            // New library entries can only be added through the
11252                            // system image.  This is important to get rid of a lot
11253                            // of nasty edge cases: for example if we allowed a non-
11254                            // system update of the app to add a library, then uninstalling
11255                            // the update would make the library go away, and assumptions
11256                            // we made such as through app install filtering would now
11257                            // have allowed apps on the device which aren't compatible
11258                            // with it.  Better to just have the restriction here, be
11259                            // conservative, and create many fewer cases that can negatively
11260                            // impact the user experience.
11261                            final PackageSetting sysPs = mSettings
11262                                    .getDisabledSystemPkgLPr(pkg.packageName);
11263                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11264                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11265                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11266                                        allowed = true;
11267                                        break;
11268                                    }
11269                                }
11270                            }
11271                        } else {
11272                            allowed = true;
11273                        }
11274                        if (allowed) {
11275                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11276                                    SharedLibraryInfo.VERSION_UNDEFINED,
11277                                    SharedLibraryInfo.TYPE_DYNAMIC,
11278                                    pkg.packageName, pkg.getLongVersionCode())) {
11279                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11280                                        + name + " already exists; skipping");
11281                            }
11282                        } else {
11283                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11284                                    + name + " that is not declared on system image; skipping");
11285                        }
11286                    }
11287
11288                    if ((scanFlags & SCAN_BOOTING) == 0) {
11289                        // If we are not booting, we need to update any applications
11290                        // that are clients of our shared library.  If we are booting,
11291                        // this will all be done once the scan is complete.
11292                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11293                    }
11294                }
11295            }
11296        }
11297
11298        if ((scanFlags & SCAN_BOOTING) != 0) {
11299            // No apps can run during boot scan, so they don't need to be frozen
11300        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11301            // Caller asked to not kill app, so it's probably not frozen
11302        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11303            // Caller asked us to ignore frozen check for some reason; they
11304            // probably didn't know the package name
11305        } else {
11306            // We're doing major surgery on this package, so it better be frozen
11307            // right now to keep it from launching
11308            checkPackageFrozen(pkgName);
11309        }
11310
11311        // Also need to kill any apps that are dependent on the library.
11312        if (clientLibPkgs != null) {
11313            for (int i=0; i<clientLibPkgs.size(); i++) {
11314                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11315                killApplication(clientPkg.applicationInfo.packageName,
11316                        clientPkg.applicationInfo.uid, "update lib");
11317            }
11318        }
11319
11320        // writer
11321        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11322
11323        synchronized (mPackages) {
11324            // We don't expect installation to fail beyond this point
11325
11326            // Add the new setting to mSettings
11327            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11328            // Add the new setting to mPackages
11329            mPackages.put(pkg.applicationInfo.packageName, pkg);
11330            // Make sure we don't accidentally delete its data.
11331            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11332            while (iter.hasNext()) {
11333                PackageCleanItem item = iter.next();
11334                if (pkgName.equals(item.packageName)) {
11335                    iter.remove();
11336                }
11337            }
11338
11339            // Add the package's KeySets to the global KeySetManagerService
11340            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11341            ksms.addScannedPackageLPw(pkg);
11342
11343            int N = pkg.providers.size();
11344            StringBuilder r = null;
11345            int i;
11346            for (i=0; i<N; i++) {
11347                PackageParser.Provider p = pkg.providers.get(i);
11348                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11349                        p.info.processName);
11350                mProviders.addProvider(p);
11351                p.syncable = p.info.isSyncable;
11352                if (p.info.authority != null) {
11353                    String names[] = p.info.authority.split(";");
11354                    p.info.authority = null;
11355                    for (int j = 0; j < names.length; j++) {
11356                        if (j == 1 && p.syncable) {
11357                            // We only want the first authority for a provider to possibly be
11358                            // syncable, so if we already added this provider using a different
11359                            // authority clear the syncable flag. We copy the provider before
11360                            // changing it because the mProviders object contains a reference
11361                            // to a provider that we don't want to change.
11362                            // Only do this for the second authority since the resulting provider
11363                            // object can be the same for all future authorities for this provider.
11364                            p = new PackageParser.Provider(p);
11365                            p.syncable = false;
11366                        }
11367                        if (!mProvidersByAuthority.containsKey(names[j])) {
11368                            mProvidersByAuthority.put(names[j], p);
11369                            if (p.info.authority == null) {
11370                                p.info.authority = names[j];
11371                            } else {
11372                                p.info.authority = p.info.authority + ";" + names[j];
11373                            }
11374                            if (DEBUG_PACKAGE_SCANNING) {
11375                                if (chatty)
11376                                    Log.d(TAG, "Registered content provider: " + names[j]
11377                                            + ", className = " + p.info.name + ", isSyncable = "
11378                                            + p.info.isSyncable);
11379                            }
11380                        } else {
11381                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11382                            Slog.w(TAG, "Skipping provider name " + names[j] +
11383                                    " (in package " + pkg.applicationInfo.packageName +
11384                                    "): name already used by "
11385                                    + ((other != null && other.getComponentName() != null)
11386                                            ? other.getComponentName().getPackageName() : "?"));
11387                        }
11388                    }
11389                }
11390                if (chatty) {
11391                    if (r == null) {
11392                        r = new StringBuilder(256);
11393                    } else {
11394                        r.append(' ');
11395                    }
11396                    r.append(p.info.name);
11397                }
11398            }
11399            if (r != null) {
11400                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11401            }
11402
11403            N = pkg.services.size();
11404            r = null;
11405            for (i=0; i<N; i++) {
11406                PackageParser.Service s = pkg.services.get(i);
11407                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11408                        s.info.processName);
11409                mServices.addService(s);
11410                if (chatty) {
11411                    if (r == null) {
11412                        r = new StringBuilder(256);
11413                    } else {
11414                        r.append(' ');
11415                    }
11416                    r.append(s.info.name);
11417                }
11418            }
11419            if (r != null) {
11420                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11421            }
11422
11423            N = pkg.receivers.size();
11424            r = null;
11425            for (i=0; i<N; i++) {
11426                PackageParser.Activity a = pkg.receivers.get(i);
11427                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11428                        a.info.processName);
11429                mReceivers.addActivity(a, "receiver");
11430                if (chatty) {
11431                    if (r == null) {
11432                        r = new StringBuilder(256);
11433                    } else {
11434                        r.append(' ');
11435                    }
11436                    r.append(a.info.name);
11437                }
11438            }
11439            if (r != null) {
11440                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11441            }
11442
11443            N = pkg.activities.size();
11444            r = null;
11445            for (i=0; i<N; i++) {
11446                PackageParser.Activity a = pkg.activities.get(i);
11447                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11448                        a.info.processName);
11449                mActivities.addActivity(a, "activity");
11450                if (chatty) {
11451                    if (r == null) {
11452                        r = new StringBuilder(256);
11453                    } else {
11454                        r.append(' ');
11455                    }
11456                    r.append(a.info.name);
11457                }
11458            }
11459            if (r != null) {
11460                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11461            }
11462
11463            // Don't allow ephemeral applications to define new permissions groups.
11464            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11465                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11466                        + " ignored: instant apps cannot define new permission groups.");
11467            } else {
11468                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11469            }
11470
11471            // Don't allow ephemeral applications to define new permissions.
11472            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11473                Slog.w(TAG, "Permissions from package " + pkg.packageName
11474                        + " ignored: instant apps cannot define new permissions.");
11475            } else {
11476                mPermissionManager.addAllPermissions(pkg, chatty);
11477            }
11478
11479            N = pkg.instrumentation.size();
11480            r = null;
11481            for (i=0; i<N; i++) {
11482                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11483                a.info.packageName = pkg.applicationInfo.packageName;
11484                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11485                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11486                a.info.splitNames = pkg.splitNames;
11487                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11488                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11489                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11490                a.info.dataDir = pkg.applicationInfo.dataDir;
11491                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11492                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11493                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11494                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11495                mInstrumentation.put(a.getComponentName(), a);
11496                if (chatty) {
11497                    if (r == null) {
11498                        r = new StringBuilder(256);
11499                    } else {
11500                        r.append(' ');
11501                    }
11502                    r.append(a.info.name);
11503                }
11504            }
11505            if (r != null) {
11506                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11507            }
11508
11509            if (pkg.protectedBroadcasts != null) {
11510                N = pkg.protectedBroadcasts.size();
11511                synchronized (mProtectedBroadcasts) {
11512                    for (i = 0; i < N; i++) {
11513                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11514                    }
11515                }
11516            }
11517        }
11518
11519        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11520    }
11521
11522    /**
11523     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11524     * is derived purely on the basis of the contents of {@code scanFile} and
11525     * {@code cpuAbiOverride}.
11526     *
11527     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11528     */
11529    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11530            boolean extractLibs)
11531                    throws PackageManagerException {
11532        // Give ourselves some initial paths; we'll come back for another
11533        // pass once we've determined ABI below.
11534        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11535
11536        // We would never need to extract libs for forward-locked and external packages,
11537        // since the container service will do it for us. We shouldn't attempt to
11538        // extract libs from system app when it was not updated.
11539        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11540                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11541            extractLibs = false;
11542        }
11543
11544        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11545        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11546
11547        NativeLibraryHelper.Handle handle = null;
11548        try {
11549            handle = NativeLibraryHelper.Handle.create(pkg);
11550            // TODO(multiArch): This can be null for apps that didn't go through the
11551            // usual installation process. We can calculate it again, like we
11552            // do during install time.
11553            //
11554            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11555            // unnecessary.
11556            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11557
11558            // Null out the abis so that they can be recalculated.
11559            pkg.applicationInfo.primaryCpuAbi = null;
11560            pkg.applicationInfo.secondaryCpuAbi = null;
11561            if (isMultiArch(pkg.applicationInfo)) {
11562                // Warn if we've set an abiOverride for multi-lib packages..
11563                // By definition, we need to copy both 32 and 64 bit libraries for
11564                // such packages.
11565                if (pkg.cpuAbiOverride != null
11566                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11567                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11568                }
11569
11570                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11571                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11572                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11573                    if (extractLibs) {
11574                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11575                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11576                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11577                                useIsaSpecificSubdirs);
11578                    } else {
11579                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11580                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11581                    }
11582                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11583                }
11584
11585                // Shared library native code should be in the APK zip aligned
11586                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11587                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11588                            "Shared library native lib extraction not supported");
11589                }
11590
11591                maybeThrowExceptionForMultiArchCopy(
11592                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11593
11594                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11595                    if (extractLibs) {
11596                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11597                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11598                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11599                                useIsaSpecificSubdirs);
11600                    } else {
11601                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11602                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11603                    }
11604                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11605                }
11606
11607                maybeThrowExceptionForMultiArchCopy(
11608                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11609
11610                if (abi64 >= 0) {
11611                    // Shared library native libs should be in the APK zip aligned
11612                    if (extractLibs && pkg.isLibrary()) {
11613                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11614                                "Shared library native lib extraction not supported");
11615                    }
11616                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11617                }
11618
11619                if (abi32 >= 0) {
11620                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11621                    if (abi64 >= 0) {
11622                        if (pkg.use32bitAbi) {
11623                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11624                            pkg.applicationInfo.primaryCpuAbi = abi;
11625                        } else {
11626                            pkg.applicationInfo.secondaryCpuAbi = abi;
11627                        }
11628                    } else {
11629                        pkg.applicationInfo.primaryCpuAbi = abi;
11630                    }
11631                }
11632            } else {
11633                String[] abiList = (cpuAbiOverride != null) ?
11634                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11635
11636                // Enable gross and lame hacks for apps that are built with old
11637                // SDK tools. We must scan their APKs for renderscript bitcode and
11638                // not launch them if it's present. Don't bother checking on devices
11639                // that don't have 64 bit support.
11640                boolean needsRenderScriptOverride = false;
11641                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11642                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11643                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11644                    needsRenderScriptOverride = true;
11645                }
11646
11647                final int copyRet;
11648                if (extractLibs) {
11649                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11650                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11651                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11652                } else {
11653                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11654                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11655                }
11656                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11657
11658                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11659                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11660                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11661                }
11662
11663                if (copyRet >= 0) {
11664                    // Shared libraries that have native libs must be multi-architecture
11665                    if (pkg.isLibrary()) {
11666                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11667                                "Shared library with native libs must be multiarch");
11668                    }
11669                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11670                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11671                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11672                } else if (needsRenderScriptOverride) {
11673                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11674                }
11675            }
11676        } catch (IOException ioe) {
11677            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11678        } finally {
11679            IoUtils.closeQuietly(handle);
11680        }
11681
11682        // Now that we've calculated the ABIs and determined if it's an internal app,
11683        // we will go ahead and populate the nativeLibraryPath.
11684        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11685    }
11686
11687    /**
11688     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11689     * i.e, so that all packages can be run inside a single process if required.
11690     *
11691     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11692     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11693     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11694     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11695     * updating a package that belongs to a shared user.
11696     *
11697     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11698     * adds unnecessary complexity.
11699     */
11700    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11701            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11702        List<String> changedAbiCodePath = null;
11703        String requiredInstructionSet = null;
11704        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11705            requiredInstructionSet = VMRuntime.getInstructionSet(
11706                     scannedPackage.applicationInfo.primaryCpuAbi);
11707        }
11708
11709        PackageSetting requirer = null;
11710        for (PackageSetting ps : packagesForUser) {
11711            // If packagesForUser contains scannedPackage, we skip it. This will happen
11712            // when scannedPackage is an update of an existing package. Without this check,
11713            // we will never be able to change the ABI of any package belonging to a shared
11714            // user, even if it's compatible with other packages.
11715            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11716                if (ps.primaryCpuAbiString == null) {
11717                    continue;
11718                }
11719
11720                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11721                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11722                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11723                    // this but there's not much we can do.
11724                    String errorMessage = "Instruction set mismatch, "
11725                            + ((requirer == null) ? "[caller]" : requirer)
11726                            + " requires " + requiredInstructionSet + " whereas " + ps
11727                            + " requires " + instructionSet;
11728                    Slog.w(TAG, errorMessage);
11729                }
11730
11731                if (requiredInstructionSet == null) {
11732                    requiredInstructionSet = instructionSet;
11733                    requirer = ps;
11734                }
11735            }
11736        }
11737
11738        if (requiredInstructionSet != null) {
11739            String adjustedAbi;
11740            if (requirer != null) {
11741                // requirer != null implies that either scannedPackage was null or that scannedPackage
11742                // did not require an ABI, in which case we have to adjust scannedPackage to match
11743                // the ABI of the set (which is the same as requirer's ABI)
11744                adjustedAbi = requirer.primaryCpuAbiString;
11745                if (scannedPackage != null) {
11746                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11747                }
11748            } else {
11749                // requirer == null implies that we're updating all ABIs in the set to
11750                // match scannedPackage.
11751                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11752            }
11753
11754            for (PackageSetting ps : packagesForUser) {
11755                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11756                    if (ps.primaryCpuAbiString != null) {
11757                        continue;
11758                    }
11759
11760                    ps.primaryCpuAbiString = adjustedAbi;
11761                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11762                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11763                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11764                        if (DEBUG_ABI_SELECTION) {
11765                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11766                                    + " (requirer="
11767                                    + (requirer != null ? requirer.pkg : "null")
11768                                    + ", scannedPackage="
11769                                    + (scannedPackage != null ? scannedPackage : "null")
11770                                    + ")");
11771                        }
11772                        if (changedAbiCodePath == null) {
11773                            changedAbiCodePath = new ArrayList<>();
11774                        }
11775                        changedAbiCodePath.add(ps.codePathString);
11776                    }
11777                }
11778            }
11779        }
11780        return changedAbiCodePath;
11781    }
11782
11783    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11784        synchronized (mPackages) {
11785            mResolverReplaced = true;
11786            // Set up information for custom user intent resolution activity.
11787            mResolveActivity.applicationInfo = pkg.applicationInfo;
11788            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11789            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11790            mResolveActivity.processName = pkg.applicationInfo.packageName;
11791            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11792            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11793                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11794            mResolveActivity.theme = 0;
11795            mResolveActivity.exported = true;
11796            mResolveActivity.enabled = true;
11797            mResolveInfo.activityInfo = mResolveActivity;
11798            mResolveInfo.priority = 0;
11799            mResolveInfo.preferredOrder = 0;
11800            mResolveInfo.match = 0;
11801            mResolveComponentName = mCustomResolverComponentName;
11802            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11803                    mResolveComponentName);
11804        }
11805    }
11806
11807    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11808        if (installerActivity == null) {
11809            if (DEBUG_INSTANT) {
11810                Slog.d(TAG, "Clear ephemeral installer activity");
11811            }
11812            mInstantAppInstallerActivity = null;
11813            return;
11814        }
11815
11816        if (DEBUG_INSTANT) {
11817            Slog.d(TAG, "Set ephemeral installer activity: "
11818                    + installerActivity.getComponentName());
11819        }
11820        // Set up information for ephemeral installer activity
11821        mInstantAppInstallerActivity = installerActivity;
11822        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11823                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11824        mInstantAppInstallerActivity.exported = true;
11825        mInstantAppInstallerActivity.enabled = true;
11826        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11827        mInstantAppInstallerInfo.priority = 1;
11828        mInstantAppInstallerInfo.preferredOrder = 1;
11829        mInstantAppInstallerInfo.isDefault = true;
11830        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11831                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11832    }
11833
11834    private static String calculateBundledApkRoot(final String codePathString) {
11835        final File codePath = new File(codePathString);
11836        final File codeRoot;
11837        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11838            codeRoot = Environment.getRootDirectory();
11839        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11840            codeRoot = Environment.getOemDirectory();
11841        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11842            codeRoot = Environment.getVendorDirectory();
11843        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11844            codeRoot = Environment.getOdmDirectory();
11845        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11846            codeRoot = Environment.getProductDirectory();
11847        } else {
11848            // Unrecognized code path; take its top real segment as the apk root:
11849            // e.g. /something/app/blah.apk => /something
11850            try {
11851                File f = codePath.getCanonicalFile();
11852                File parent = f.getParentFile();    // non-null because codePath is a file
11853                File tmp;
11854                while ((tmp = parent.getParentFile()) != null) {
11855                    f = parent;
11856                    parent = tmp;
11857                }
11858                codeRoot = f;
11859                Slog.w(TAG, "Unrecognized code path "
11860                        + codePath + " - using " + codeRoot);
11861            } catch (IOException e) {
11862                // Can't canonicalize the code path -- shenanigans?
11863                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11864                return Environment.getRootDirectory().getPath();
11865            }
11866        }
11867        return codeRoot.getPath();
11868    }
11869
11870    /**
11871     * Derive and set the location of native libraries for the given package,
11872     * which varies depending on where and how the package was installed.
11873     */
11874    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11875        final ApplicationInfo info = pkg.applicationInfo;
11876        final String codePath = pkg.codePath;
11877        final File codeFile = new File(codePath);
11878        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11879        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11880
11881        info.nativeLibraryRootDir = null;
11882        info.nativeLibraryRootRequiresIsa = false;
11883        info.nativeLibraryDir = null;
11884        info.secondaryNativeLibraryDir = null;
11885
11886        if (isApkFile(codeFile)) {
11887            // Monolithic install
11888            if (bundledApp) {
11889                // If "/system/lib64/apkname" exists, assume that is the per-package
11890                // native library directory to use; otherwise use "/system/lib/apkname".
11891                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11892                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11893                        getPrimaryInstructionSet(info));
11894
11895                // This is a bundled system app so choose the path based on the ABI.
11896                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11897                // is just the default path.
11898                final String apkName = deriveCodePathName(codePath);
11899                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11900                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11901                        apkName).getAbsolutePath();
11902
11903                if (info.secondaryCpuAbi != null) {
11904                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11905                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11906                            secondaryLibDir, apkName).getAbsolutePath();
11907                }
11908            } else if (asecApp) {
11909                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11910                        .getAbsolutePath();
11911            } else {
11912                final String apkName = deriveCodePathName(codePath);
11913                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11914                        .getAbsolutePath();
11915            }
11916
11917            info.nativeLibraryRootRequiresIsa = false;
11918            info.nativeLibraryDir = info.nativeLibraryRootDir;
11919        } else {
11920            // Cluster install
11921            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11922            info.nativeLibraryRootRequiresIsa = true;
11923
11924            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11925                    getPrimaryInstructionSet(info)).getAbsolutePath();
11926
11927            if (info.secondaryCpuAbi != null) {
11928                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11929                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11930            }
11931        }
11932    }
11933
11934    /**
11935     * Calculate the abis and roots for a bundled app. These can uniquely
11936     * be determined from the contents of the system partition, i.e whether
11937     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11938     * of this information, and instead assume that the system was built
11939     * sensibly.
11940     */
11941    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11942                                           PackageSetting pkgSetting) {
11943        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11944
11945        // If "/system/lib64/apkname" exists, assume that is the per-package
11946        // native library directory to use; otherwise use "/system/lib/apkname".
11947        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11948        setBundledAppAbi(pkg, apkRoot, apkName);
11949        // pkgSetting might be null during rescan following uninstall of updates
11950        // to a bundled app, so accommodate that possibility.  The settings in
11951        // that case will be established later from the parsed package.
11952        //
11953        // If the settings aren't null, sync them up with what we've just derived.
11954        // note that apkRoot isn't stored in the package settings.
11955        if (pkgSetting != null) {
11956            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11957            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11958        }
11959    }
11960
11961    /**
11962     * Deduces the ABI of a bundled app and sets the relevant fields on the
11963     * parsed pkg object.
11964     *
11965     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11966     *        under which system libraries are installed.
11967     * @param apkName the name of the installed package.
11968     */
11969    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11970        final File codeFile = new File(pkg.codePath);
11971
11972        final boolean has64BitLibs;
11973        final boolean has32BitLibs;
11974        if (isApkFile(codeFile)) {
11975            // Monolithic install
11976            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11977            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11978        } else {
11979            // Cluster install
11980            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11981            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11982                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11983                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11984                has64BitLibs = (new File(rootDir, isa)).exists();
11985            } else {
11986                has64BitLibs = false;
11987            }
11988            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11989                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11990                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11991                has32BitLibs = (new File(rootDir, isa)).exists();
11992            } else {
11993                has32BitLibs = false;
11994            }
11995        }
11996
11997        if (has64BitLibs && !has32BitLibs) {
11998            // The package has 64 bit libs, but not 32 bit libs. Its primary
11999            // ABI should be 64 bit. We can safely assume here that the bundled
12000            // native libraries correspond to the most preferred ABI in the list.
12001
12002            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12003            pkg.applicationInfo.secondaryCpuAbi = null;
12004        } else if (has32BitLibs && !has64BitLibs) {
12005            // The package has 32 bit libs but not 64 bit libs. Its primary
12006            // ABI should be 32 bit.
12007
12008            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12009            pkg.applicationInfo.secondaryCpuAbi = null;
12010        } else if (has32BitLibs && has64BitLibs) {
12011            // The application has both 64 and 32 bit bundled libraries. We check
12012            // here that the app declares multiArch support, and warn if it doesn't.
12013            //
12014            // We will be lenient here and record both ABIs. The primary will be the
12015            // ABI that's higher on the list, i.e, a device that's configured to prefer
12016            // 64 bit apps will see a 64 bit primary ABI,
12017
12018            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12019                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12020            }
12021
12022            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12023                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12024                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12025            } else {
12026                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12027                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12028            }
12029        } else {
12030            pkg.applicationInfo.primaryCpuAbi = null;
12031            pkg.applicationInfo.secondaryCpuAbi = null;
12032        }
12033    }
12034
12035    private void killApplication(String pkgName, int appId, String reason) {
12036        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12037    }
12038
12039    private void killApplication(String pkgName, int appId, int userId, String reason) {
12040        // Request the ActivityManager to kill the process(only for existing packages)
12041        // so that we do not end up in a confused state while the user is still using the older
12042        // version of the application while the new one gets installed.
12043        final long token = Binder.clearCallingIdentity();
12044        try {
12045            IActivityManager am = ActivityManager.getService();
12046            if (am != null) {
12047                try {
12048                    am.killApplication(pkgName, appId, userId, reason);
12049                } catch (RemoteException e) {
12050                }
12051            }
12052        } finally {
12053            Binder.restoreCallingIdentity(token);
12054        }
12055    }
12056
12057    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12058        // Remove the parent package setting
12059        PackageSetting ps = (PackageSetting) pkg.mExtras;
12060        if (ps != null) {
12061            removePackageLI(ps, chatty);
12062        }
12063        // Remove the child package setting
12064        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12065        for (int i = 0; i < childCount; i++) {
12066            PackageParser.Package childPkg = pkg.childPackages.get(i);
12067            ps = (PackageSetting) childPkg.mExtras;
12068            if (ps != null) {
12069                removePackageLI(ps, chatty);
12070            }
12071        }
12072    }
12073
12074    void removePackageLI(PackageSetting ps, boolean chatty) {
12075        if (DEBUG_INSTALL) {
12076            if (chatty)
12077                Log.d(TAG, "Removing package " + ps.name);
12078        }
12079
12080        // writer
12081        synchronized (mPackages) {
12082            mPackages.remove(ps.name);
12083            final PackageParser.Package pkg = ps.pkg;
12084            if (pkg != null) {
12085                cleanPackageDataStructuresLILPw(pkg, chatty);
12086            }
12087        }
12088    }
12089
12090    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12091        if (DEBUG_INSTALL) {
12092            if (chatty)
12093                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12094        }
12095
12096        // writer
12097        synchronized (mPackages) {
12098            // Remove the parent package
12099            mPackages.remove(pkg.applicationInfo.packageName);
12100            cleanPackageDataStructuresLILPw(pkg, chatty);
12101
12102            // Remove the child packages
12103            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12104            for (int i = 0; i < childCount; i++) {
12105                PackageParser.Package childPkg = pkg.childPackages.get(i);
12106                mPackages.remove(childPkg.applicationInfo.packageName);
12107                cleanPackageDataStructuresLILPw(childPkg, chatty);
12108            }
12109        }
12110    }
12111
12112    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12113        int N = pkg.providers.size();
12114        StringBuilder r = null;
12115        int i;
12116        for (i=0; i<N; i++) {
12117            PackageParser.Provider p = pkg.providers.get(i);
12118            mProviders.removeProvider(p);
12119            if (p.info.authority == null) {
12120
12121                /* There was another ContentProvider with this authority when
12122                 * this app was installed so this authority is null,
12123                 * Ignore it as we don't have to unregister the provider.
12124                 */
12125                continue;
12126            }
12127            String names[] = p.info.authority.split(";");
12128            for (int j = 0; j < names.length; j++) {
12129                if (mProvidersByAuthority.get(names[j]) == p) {
12130                    mProvidersByAuthority.remove(names[j]);
12131                    if (DEBUG_REMOVE) {
12132                        if (chatty)
12133                            Log.d(TAG, "Unregistered content provider: " + names[j]
12134                                    + ", className = " + p.info.name + ", isSyncable = "
12135                                    + p.info.isSyncable);
12136                    }
12137                }
12138            }
12139            if (DEBUG_REMOVE && chatty) {
12140                if (r == null) {
12141                    r = new StringBuilder(256);
12142                } else {
12143                    r.append(' ');
12144                }
12145                r.append(p.info.name);
12146            }
12147        }
12148        if (r != null) {
12149            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12150        }
12151
12152        N = pkg.services.size();
12153        r = null;
12154        for (i=0; i<N; i++) {
12155            PackageParser.Service s = pkg.services.get(i);
12156            mServices.removeService(s);
12157            if (chatty) {
12158                if (r == null) {
12159                    r = new StringBuilder(256);
12160                } else {
12161                    r.append(' ');
12162                }
12163                r.append(s.info.name);
12164            }
12165        }
12166        if (r != null) {
12167            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12168        }
12169
12170        N = pkg.receivers.size();
12171        r = null;
12172        for (i=0; i<N; i++) {
12173            PackageParser.Activity a = pkg.receivers.get(i);
12174            mReceivers.removeActivity(a, "receiver");
12175            if (DEBUG_REMOVE && chatty) {
12176                if (r == null) {
12177                    r = new StringBuilder(256);
12178                } else {
12179                    r.append(' ');
12180                }
12181                r.append(a.info.name);
12182            }
12183        }
12184        if (r != null) {
12185            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12186        }
12187
12188        N = pkg.activities.size();
12189        r = null;
12190        for (i=0; i<N; i++) {
12191            PackageParser.Activity a = pkg.activities.get(i);
12192            mActivities.removeActivity(a, "activity");
12193            if (DEBUG_REMOVE && chatty) {
12194                if (r == null) {
12195                    r = new StringBuilder(256);
12196                } else {
12197                    r.append(' ');
12198                }
12199                r.append(a.info.name);
12200            }
12201        }
12202        if (r != null) {
12203            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12204        }
12205
12206        mPermissionManager.removeAllPermissions(pkg, chatty);
12207
12208        N = pkg.instrumentation.size();
12209        r = null;
12210        for (i=0; i<N; i++) {
12211            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12212            mInstrumentation.remove(a.getComponentName());
12213            if (DEBUG_REMOVE && chatty) {
12214                if (r == null) {
12215                    r = new StringBuilder(256);
12216                } else {
12217                    r.append(' ');
12218                }
12219                r.append(a.info.name);
12220            }
12221        }
12222        if (r != null) {
12223            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12224        }
12225
12226        r = null;
12227        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12228            // Only system apps can hold shared libraries.
12229            if (pkg.libraryNames != null) {
12230                for (i = 0; i < pkg.libraryNames.size(); i++) {
12231                    String name = pkg.libraryNames.get(i);
12232                    if (removeSharedLibraryLPw(name, 0)) {
12233                        if (DEBUG_REMOVE && chatty) {
12234                            if (r == null) {
12235                                r = new StringBuilder(256);
12236                            } else {
12237                                r.append(' ');
12238                            }
12239                            r.append(name);
12240                        }
12241                    }
12242                }
12243            }
12244        }
12245
12246        r = null;
12247
12248        // Any package can hold static shared libraries.
12249        if (pkg.staticSharedLibName != null) {
12250            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12251                if (DEBUG_REMOVE && chatty) {
12252                    if (r == null) {
12253                        r = new StringBuilder(256);
12254                    } else {
12255                        r.append(' ');
12256                    }
12257                    r.append(pkg.staticSharedLibName);
12258                }
12259            }
12260        }
12261
12262        if (r != null) {
12263            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12264        }
12265    }
12266
12267
12268    final class ActivityIntentResolver
12269            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12270        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12271                boolean defaultOnly, int userId) {
12272            if (!sUserManager.exists(userId)) return null;
12273            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12274            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12275        }
12276
12277        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12278                int userId) {
12279            if (!sUserManager.exists(userId)) return null;
12280            mFlags = flags;
12281            return super.queryIntent(intent, resolvedType,
12282                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12283                    userId);
12284        }
12285
12286        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12287                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12288            if (!sUserManager.exists(userId)) return null;
12289            if (packageActivities == null) {
12290                return null;
12291            }
12292            mFlags = flags;
12293            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12294            final int N = packageActivities.size();
12295            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12296                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12297
12298            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12299            for (int i = 0; i < N; ++i) {
12300                intentFilters = packageActivities.get(i).intents;
12301                if (intentFilters != null && intentFilters.size() > 0) {
12302                    PackageParser.ActivityIntentInfo[] array =
12303                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12304                    intentFilters.toArray(array);
12305                    listCut.add(array);
12306                }
12307            }
12308            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12309        }
12310
12311        /**
12312         * Finds a privileged activity that matches the specified activity names.
12313         */
12314        private PackageParser.Activity findMatchingActivity(
12315                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12316            for (PackageParser.Activity sysActivity : activityList) {
12317                if (sysActivity.info.name.equals(activityInfo.name)) {
12318                    return sysActivity;
12319                }
12320                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12321                    return sysActivity;
12322                }
12323                if (sysActivity.info.targetActivity != null) {
12324                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12325                        return sysActivity;
12326                    }
12327                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12328                        return sysActivity;
12329                    }
12330                }
12331            }
12332            return null;
12333        }
12334
12335        public class IterGenerator<E> {
12336            public Iterator<E> generate(ActivityIntentInfo info) {
12337                return null;
12338            }
12339        }
12340
12341        public class ActionIterGenerator extends IterGenerator<String> {
12342            @Override
12343            public Iterator<String> generate(ActivityIntentInfo info) {
12344                return info.actionsIterator();
12345            }
12346        }
12347
12348        public class CategoriesIterGenerator extends IterGenerator<String> {
12349            @Override
12350            public Iterator<String> generate(ActivityIntentInfo info) {
12351                return info.categoriesIterator();
12352            }
12353        }
12354
12355        public class SchemesIterGenerator extends IterGenerator<String> {
12356            @Override
12357            public Iterator<String> generate(ActivityIntentInfo info) {
12358                return info.schemesIterator();
12359            }
12360        }
12361
12362        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12363            @Override
12364            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12365                return info.authoritiesIterator();
12366            }
12367        }
12368
12369        /**
12370         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12371         * MODIFIED. Do not pass in a list that should not be changed.
12372         */
12373        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12374                IterGenerator<T> generator, Iterator<T> searchIterator) {
12375            // loop through the set of actions; every one must be found in the intent filter
12376            while (searchIterator.hasNext()) {
12377                // we must have at least one filter in the list to consider a match
12378                if (intentList.size() == 0) {
12379                    break;
12380                }
12381
12382                final T searchAction = searchIterator.next();
12383
12384                // loop through the set of intent filters
12385                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12386                while (intentIter.hasNext()) {
12387                    final ActivityIntentInfo intentInfo = intentIter.next();
12388                    boolean selectionFound = false;
12389
12390                    // loop through the intent filter's selection criteria; at least one
12391                    // of them must match the searched criteria
12392                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12393                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12394                        final T intentSelection = intentSelectionIter.next();
12395                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12396                            selectionFound = true;
12397                            break;
12398                        }
12399                    }
12400
12401                    // the selection criteria wasn't found in this filter's set; this filter
12402                    // is not a potential match
12403                    if (!selectionFound) {
12404                        intentIter.remove();
12405                    }
12406                }
12407            }
12408        }
12409
12410        private boolean isProtectedAction(ActivityIntentInfo filter) {
12411            final Iterator<String> actionsIter = filter.actionsIterator();
12412            while (actionsIter != null && actionsIter.hasNext()) {
12413                final String filterAction = actionsIter.next();
12414                if (PROTECTED_ACTIONS.contains(filterAction)) {
12415                    return true;
12416                }
12417            }
12418            return false;
12419        }
12420
12421        /**
12422         * Adjusts the priority of the given intent filter according to policy.
12423         * <p>
12424         * <ul>
12425         * <li>The priority for non privileged applications is capped to '0'</li>
12426         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12427         * <li>The priority for unbundled updates to privileged applications is capped to the
12428         *      priority defined on the system partition</li>
12429         * </ul>
12430         * <p>
12431         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12432         * allowed to obtain any priority on any action.
12433         */
12434        private void adjustPriority(
12435                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12436            // nothing to do; priority is fine as-is
12437            if (intent.getPriority() <= 0) {
12438                return;
12439            }
12440
12441            final ActivityInfo activityInfo = intent.activity.info;
12442            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12443
12444            final boolean privilegedApp =
12445                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12446            if (!privilegedApp) {
12447                // non-privileged applications can never define a priority >0
12448                if (DEBUG_FILTERS) {
12449                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12450                            + " package: " + applicationInfo.packageName
12451                            + " activity: " + intent.activity.className
12452                            + " origPrio: " + intent.getPriority());
12453                }
12454                intent.setPriority(0);
12455                return;
12456            }
12457
12458            if (systemActivities == null) {
12459                // the system package is not disabled; we're parsing the system partition
12460                if (isProtectedAction(intent)) {
12461                    if (mDeferProtectedFilters) {
12462                        // We can't deal with these just yet. No component should ever obtain a
12463                        // >0 priority for a protected actions, with ONE exception -- the setup
12464                        // wizard. The setup wizard, however, cannot be known until we're able to
12465                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12466                        // until all intent filters have been processed. Chicken, meet egg.
12467                        // Let the filter temporarily have a high priority and rectify the
12468                        // priorities after all system packages have been scanned.
12469                        mProtectedFilters.add(intent);
12470                        if (DEBUG_FILTERS) {
12471                            Slog.i(TAG, "Protected action; save for later;"
12472                                    + " package: " + applicationInfo.packageName
12473                                    + " activity: " + intent.activity.className
12474                                    + " origPrio: " + intent.getPriority());
12475                        }
12476                        return;
12477                    } else {
12478                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12479                            Slog.i(TAG, "No setup wizard;"
12480                                + " All protected intents capped to priority 0");
12481                        }
12482                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12483                            if (DEBUG_FILTERS) {
12484                                Slog.i(TAG, "Found setup wizard;"
12485                                    + " allow priority " + intent.getPriority() + ";"
12486                                    + " package: " + intent.activity.info.packageName
12487                                    + " activity: " + intent.activity.className
12488                                    + " priority: " + intent.getPriority());
12489                            }
12490                            // setup wizard gets whatever it wants
12491                            return;
12492                        }
12493                        if (DEBUG_FILTERS) {
12494                            Slog.i(TAG, "Protected action; cap priority to 0;"
12495                                    + " package: " + intent.activity.info.packageName
12496                                    + " activity: " + intent.activity.className
12497                                    + " origPrio: " + intent.getPriority());
12498                        }
12499                        intent.setPriority(0);
12500                        return;
12501                    }
12502                }
12503                // privileged apps on the system image get whatever priority they request
12504                return;
12505            }
12506
12507            // privileged app unbundled update ... try to find the same activity
12508            final PackageParser.Activity foundActivity =
12509                    findMatchingActivity(systemActivities, activityInfo);
12510            if (foundActivity == null) {
12511                // this is a new activity; it cannot obtain >0 priority
12512                if (DEBUG_FILTERS) {
12513                    Slog.i(TAG, "New activity; cap priority to 0;"
12514                            + " package: " + applicationInfo.packageName
12515                            + " activity: " + intent.activity.className
12516                            + " origPrio: " + intent.getPriority());
12517                }
12518                intent.setPriority(0);
12519                return;
12520            }
12521
12522            // found activity, now check for filter equivalence
12523
12524            // a shallow copy is enough; we modify the list, not its contents
12525            final List<ActivityIntentInfo> intentListCopy =
12526                    new ArrayList<>(foundActivity.intents);
12527            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12528
12529            // find matching action subsets
12530            final Iterator<String> actionsIterator = intent.actionsIterator();
12531            if (actionsIterator != null) {
12532                getIntentListSubset(
12533                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12534                if (intentListCopy.size() == 0) {
12535                    // no more intents to match; we're not equivalent
12536                    if (DEBUG_FILTERS) {
12537                        Slog.i(TAG, "Mismatched action; 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
12547            // find matching category subsets
12548            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12549            if (categoriesIterator != null) {
12550                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12551                        categoriesIterator);
12552                if (intentListCopy.size() == 0) {
12553                    // no more intents to match; we're not equivalent
12554                    if (DEBUG_FILTERS) {
12555                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12556                                + " package: " + applicationInfo.packageName
12557                                + " activity: " + intent.activity.className
12558                                + " origPrio: " + intent.getPriority());
12559                    }
12560                    intent.setPriority(0);
12561                    return;
12562                }
12563            }
12564
12565            // find matching schemes subsets
12566            final Iterator<String> schemesIterator = intent.schemesIterator();
12567            if (schemesIterator != null) {
12568                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12569                        schemesIterator);
12570                if (intentListCopy.size() == 0) {
12571                    // no more intents to match; we're not equivalent
12572                    if (DEBUG_FILTERS) {
12573                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12574                                + " package: " + applicationInfo.packageName
12575                                + " activity: " + intent.activity.className
12576                                + " origPrio: " + intent.getPriority());
12577                    }
12578                    intent.setPriority(0);
12579                    return;
12580                }
12581            }
12582
12583            // find matching authorities subsets
12584            final Iterator<IntentFilter.AuthorityEntry>
12585                    authoritiesIterator = intent.authoritiesIterator();
12586            if (authoritiesIterator != null) {
12587                getIntentListSubset(intentListCopy,
12588                        new AuthoritiesIterGenerator(),
12589                        authoritiesIterator);
12590                if (intentListCopy.size() == 0) {
12591                    // no more intents to match; we're not equivalent
12592                    if (DEBUG_FILTERS) {
12593                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12594                                + " package: " + applicationInfo.packageName
12595                                + " activity: " + intent.activity.className
12596                                + " origPrio: " + intent.getPriority());
12597                    }
12598                    intent.setPriority(0);
12599                    return;
12600                }
12601            }
12602
12603            // we found matching filter(s); app gets the max priority of all intents
12604            int cappedPriority = 0;
12605            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12606                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12607            }
12608            if (intent.getPriority() > cappedPriority) {
12609                if (DEBUG_FILTERS) {
12610                    Slog.i(TAG, "Found matching filter(s);"
12611                            + " cap priority to " + cappedPriority + ";"
12612                            + " package: " + applicationInfo.packageName
12613                            + " activity: " + intent.activity.className
12614                            + " origPrio: " + intent.getPriority());
12615                }
12616                intent.setPriority(cappedPriority);
12617                return;
12618            }
12619            // all this for nothing; the requested priority was <= what was on the system
12620        }
12621
12622        public final void addActivity(PackageParser.Activity a, String type) {
12623            mActivities.put(a.getComponentName(), a);
12624            if (DEBUG_SHOW_INFO)
12625                Log.v(
12626                TAG, "  " + type + " " +
12627                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12628            if (DEBUG_SHOW_INFO)
12629                Log.v(TAG, "    Class=" + a.info.name);
12630            final int NI = a.intents.size();
12631            for (int j=0; j<NI; j++) {
12632                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12633                if ("activity".equals(type)) {
12634                    final PackageSetting ps =
12635                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12636                    final List<PackageParser.Activity> systemActivities =
12637                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12638                    adjustPriority(systemActivities, intent);
12639                }
12640                if (DEBUG_SHOW_INFO) {
12641                    Log.v(TAG, "    IntentFilter:");
12642                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12643                }
12644                if (!intent.debugCheck()) {
12645                    Log.w(TAG, "==> For Activity " + a.info.name);
12646                }
12647                addFilter(intent);
12648            }
12649        }
12650
12651        public final void removeActivity(PackageParser.Activity a, String type) {
12652            mActivities.remove(a.getComponentName());
12653            if (DEBUG_SHOW_INFO) {
12654                Log.v(TAG, "  " + type + " "
12655                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12656                                : a.info.name) + ":");
12657                Log.v(TAG, "    Class=" + a.info.name);
12658            }
12659            final int NI = a.intents.size();
12660            for (int j=0; j<NI; j++) {
12661                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12662                if (DEBUG_SHOW_INFO) {
12663                    Log.v(TAG, "    IntentFilter:");
12664                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12665                }
12666                removeFilter(intent);
12667            }
12668        }
12669
12670        @Override
12671        protected boolean allowFilterResult(
12672                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12673            ActivityInfo filterAi = filter.activity.info;
12674            for (int i=dest.size()-1; i>=0; i--) {
12675                ActivityInfo destAi = dest.get(i).activityInfo;
12676                if (destAi.name == filterAi.name
12677                        && destAi.packageName == filterAi.packageName) {
12678                    return false;
12679                }
12680            }
12681            return true;
12682        }
12683
12684        @Override
12685        protected ActivityIntentInfo[] newArray(int size) {
12686            return new ActivityIntentInfo[size];
12687        }
12688
12689        @Override
12690        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12691            if (!sUserManager.exists(userId)) return true;
12692            PackageParser.Package p = filter.activity.owner;
12693            if (p != null) {
12694                PackageSetting ps = (PackageSetting)p.mExtras;
12695                if (ps != null) {
12696                    // System apps are never considered stopped for purposes of
12697                    // filtering, because there may be no way for the user to
12698                    // actually re-launch them.
12699                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12700                            && ps.getStopped(userId);
12701                }
12702            }
12703            return false;
12704        }
12705
12706        @Override
12707        protected boolean isPackageForFilter(String packageName,
12708                PackageParser.ActivityIntentInfo info) {
12709            return packageName.equals(info.activity.owner.packageName);
12710        }
12711
12712        @Override
12713        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12714                int match, int userId) {
12715            if (!sUserManager.exists(userId)) return null;
12716            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12717                return null;
12718            }
12719            final PackageParser.Activity activity = info.activity;
12720            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12721            if (ps == null) {
12722                return null;
12723            }
12724            final PackageUserState userState = ps.readUserState(userId);
12725            ActivityInfo ai =
12726                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12727            if (ai == null) {
12728                return null;
12729            }
12730            final boolean matchExplicitlyVisibleOnly =
12731                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12732            final boolean matchVisibleToInstantApp =
12733                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12734            final boolean componentVisible =
12735                    matchVisibleToInstantApp
12736                    && info.isVisibleToInstantApp()
12737                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12738            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12739            // throw out filters that aren't visible to ephemeral apps
12740            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12741                return null;
12742            }
12743            // throw out instant app filters if we're not explicitly requesting them
12744            if (!matchInstantApp && userState.instantApp) {
12745                return null;
12746            }
12747            // throw out instant app filters if updates are available; will trigger
12748            // instant app resolution
12749            if (userState.instantApp && ps.isUpdateAvailable()) {
12750                return null;
12751            }
12752            final ResolveInfo res = new ResolveInfo();
12753            res.activityInfo = ai;
12754            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12755                res.filter = info;
12756            }
12757            if (info != null) {
12758                res.handleAllWebDataURI = info.handleAllWebDataURI();
12759            }
12760            res.priority = info.getPriority();
12761            res.preferredOrder = activity.owner.mPreferredOrder;
12762            //System.out.println("Result: " + res.activityInfo.className +
12763            //                   " = " + res.priority);
12764            res.match = match;
12765            res.isDefault = info.hasDefault;
12766            res.labelRes = info.labelRes;
12767            res.nonLocalizedLabel = info.nonLocalizedLabel;
12768            if (userNeedsBadging(userId)) {
12769                res.noResourceId = true;
12770            } else {
12771                res.icon = info.icon;
12772            }
12773            res.iconResourceId = info.icon;
12774            res.system = res.activityInfo.applicationInfo.isSystemApp();
12775            res.isInstantAppAvailable = userState.instantApp;
12776            return res;
12777        }
12778
12779        @Override
12780        protected void sortResults(List<ResolveInfo> results) {
12781            Collections.sort(results, mResolvePrioritySorter);
12782        }
12783
12784        @Override
12785        protected void dumpFilter(PrintWriter out, String prefix,
12786                PackageParser.ActivityIntentInfo filter) {
12787            out.print(prefix); out.print(
12788                    Integer.toHexString(System.identityHashCode(filter.activity)));
12789                    out.print(' ');
12790                    filter.activity.printComponentShortName(out);
12791                    out.print(" filter ");
12792                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12793        }
12794
12795        @Override
12796        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12797            return filter.activity;
12798        }
12799
12800        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12801            PackageParser.Activity activity = (PackageParser.Activity)label;
12802            out.print(prefix); out.print(
12803                    Integer.toHexString(System.identityHashCode(activity)));
12804                    out.print(' ');
12805                    activity.printComponentShortName(out);
12806            if (count > 1) {
12807                out.print(" ("); out.print(count); out.print(" filters)");
12808            }
12809            out.println();
12810        }
12811
12812        // Keys are String (activity class name), values are Activity.
12813        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12814                = new ArrayMap<ComponentName, PackageParser.Activity>();
12815        private int mFlags;
12816    }
12817
12818    private final class ServiceIntentResolver
12819            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12820        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12821                boolean defaultOnly, int userId) {
12822            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12823            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12824        }
12825
12826        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12827                int userId) {
12828            if (!sUserManager.exists(userId)) return null;
12829            mFlags = flags;
12830            return super.queryIntent(intent, resolvedType,
12831                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12832                    userId);
12833        }
12834
12835        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12836                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12837            if (!sUserManager.exists(userId)) return null;
12838            if (packageServices == null) {
12839                return null;
12840            }
12841            mFlags = flags;
12842            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12843            final int N = packageServices.size();
12844            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12845                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12846
12847            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12848            for (int i = 0; i < N; ++i) {
12849                intentFilters = packageServices.get(i).intents;
12850                if (intentFilters != null && intentFilters.size() > 0) {
12851                    PackageParser.ServiceIntentInfo[] array =
12852                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12853                    intentFilters.toArray(array);
12854                    listCut.add(array);
12855                }
12856            }
12857            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12858        }
12859
12860        public final void addService(PackageParser.Service s) {
12861            mServices.put(s.getComponentName(), s);
12862            if (DEBUG_SHOW_INFO) {
12863                Log.v(TAG, "  "
12864                        + (s.info.nonLocalizedLabel != null
12865                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12866                Log.v(TAG, "    Class=" + s.info.name);
12867            }
12868            final int NI = s.intents.size();
12869            int j;
12870            for (j=0; j<NI; j++) {
12871                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12872                if (DEBUG_SHOW_INFO) {
12873                    Log.v(TAG, "    IntentFilter:");
12874                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12875                }
12876                if (!intent.debugCheck()) {
12877                    Log.w(TAG, "==> For Service " + s.info.name);
12878                }
12879                addFilter(intent);
12880            }
12881        }
12882
12883        public final void removeService(PackageParser.Service s) {
12884            mServices.remove(s.getComponentName());
12885            if (DEBUG_SHOW_INFO) {
12886                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12887                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12888                Log.v(TAG, "    Class=" + s.info.name);
12889            }
12890            final int NI = s.intents.size();
12891            int j;
12892            for (j=0; j<NI; j++) {
12893                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12894                if (DEBUG_SHOW_INFO) {
12895                    Log.v(TAG, "    IntentFilter:");
12896                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12897                }
12898                removeFilter(intent);
12899            }
12900        }
12901
12902        @Override
12903        protected boolean allowFilterResult(
12904                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12905            ServiceInfo filterSi = filter.service.info;
12906            for (int i=dest.size()-1; i>=0; i--) {
12907                ServiceInfo destAi = dest.get(i).serviceInfo;
12908                if (destAi.name == filterSi.name
12909                        && destAi.packageName == filterSi.packageName) {
12910                    return false;
12911                }
12912            }
12913            return true;
12914        }
12915
12916        @Override
12917        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12918            return new PackageParser.ServiceIntentInfo[size];
12919        }
12920
12921        @Override
12922        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12923            if (!sUserManager.exists(userId)) return true;
12924            PackageParser.Package p = filter.service.owner;
12925            if (p != null) {
12926                PackageSetting ps = (PackageSetting)p.mExtras;
12927                if (ps != null) {
12928                    // System apps are never considered stopped for purposes of
12929                    // filtering, because there may be no way for the user to
12930                    // actually re-launch them.
12931                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12932                            && ps.getStopped(userId);
12933                }
12934            }
12935            return false;
12936        }
12937
12938        @Override
12939        protected boolean isPackageForFilter(String packageName,
12940                PackageParser.ServiceIntentInfo info) {
12941            return packageName.equals(info.service.owner.packageName);
12942        }
12943
12944        @Override
12945        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12946                int match, int userId) {
12947            if (!sUserManager.exists(userId)) return null;
12948            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12949            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12950                return null;
12951            }
12952            final PackageParser.Service service = info.service;
12953            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12954            if (ps == null) {
12955                return null;
12956            }
12957            final PackageUserState userState = ps.readUserState(userId);
12958            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12959                    userState, userId);
12960            if (si == null) {
12961                return null;
12962            }
12963            final boolean matchVisibleToInstantApp =
12964                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12965            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12966            // throw out filters that aren't visible to ephemeral apps
12967            if (matchVisibleToInstantApp
12968                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12969                return null;
12970            }
12971            // throw out ephemeral filters if we're not explicitly requesting them
12972            if (!isInstantApp && userState.instantApp) {
12973                return null;
12974            }
12975            // throw out instant app filters if updates are available; will trigger
12976            // instant app resolution
12977            if (userState.instantApp && ps.isUpdateAvailable()) {
12978                return null;
12979            }
12980            final ResolveInfo res = new ResolveInfo();
12981            res.serviceInfo = si;
12982            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12983                res.filter = filter;
12984            }
12985            res.priority = info.getPriority();
12986            res.preferredOrder = service.owner.mPreferredOrder;
12987            res.match = match;
12988            res.isDefault = info.hasDefault;
12989            res.labelRes = info.labelRes;
12990            res.nonLocalizedLabel = info.nonLocalizedLabel;
12991            res.icon = info.icon;
12992            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12993            return res;
12994        }
12995
12996        @Override
12997        protected void sortResults(List<ResolveInfo> results) {
12998            Collections.sort(results, mResolvePrioritySorter);
12999        }
13000
13001        @Override
13002        protected void dumpFilter(PrintWriter out, String prefix,
13003                PackageParser.ServiceIntentInfo filter) {
13004            out.print(prefix); out.print(
13005                    Integer.toHexString(System.identityHashCode(filter.service)));
13006                    out.print(' ');
13007                    filter.service.printComponentShortName(out);
13008                    out.print(" filter ");
13009                    out.print(Integer.toHexString(System.identityHashCode(filter)));
13010                    if (filter.service.info.permission != null) {
13011                        out.print(" permission "); out.println(filter.service.info.permission);
13012                    } else {
13013                        out.println();
13014                    }
13015        }
13016
13017        @Override
13018        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13019            return filter.service;
13020        }
13021
13022        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13023            PackageParser.Service service = (PackageParser.Service)label;
13024            out.print(prefix); out.print(
13025                    Integer.toHexString(System.identityHashCode(service)));
13026                    out.print(' ');
13027                    service.printComponentShortName(out);
13028            if (count > 1) {
13029                out.print(" ("); out.print(count); out.print(" filters)");
13030            }
13031            out.println();
13032        }
13033
13034//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13035//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13036//            final List<ResolveInfo> retList = Lists.newArrayList();
13037//            while (i.hasNext()) {
13038//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13039//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13040//                    retList.add(resolveInfo);
13041//                }
13042//            }
13043//            return retList;
13044//        }
13045
13046        // Keys are String (activity class name), values are Activity.
13047        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13048                = new ArrayMap<ComponentName, PackageParser.Service>();
13049        private int mFlags;
13050    }
13051
13052    private final class ProviderIntentResolver
13053            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13054        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13055                boolean defaultOnly, int userId) {
13056            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13057            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13058        }
13059
13060        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13061                int userId) {
13062            if (!sUserManager.exists(userId))
13063                return null;
13064            mFlags = flags;
13065            return super.queryIntent(intent, resolvedType,
13066                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13067                    userId);
13068        }
13069
13070        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13071                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13072            if (!sUserManager.exists(userId))
13073                return null;
13074            if (packageProviders == null) {
13075                return null;
13076            }
13077            mFlags = flags;
13078            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13079            final int N = packageProviders.size();
13080            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13081                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13082
13083            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13084            for (int i = 0; i < N; ++i) {
13085                intentFilters = packageProviders.get(i).intents;
13086                if (intentFilters != null && intentFilters.size() > 0) {
13087                    PackageParser.ProviderIntentInfo[] array =
13088                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13089                    intentFilters.toArray(array);
13090                    listCut.add(array);
13091                }
13092            }
13093            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13094        }
13095
13096        public final void addProvider(PackageParser.Provider p) {
13097            if (mProviders.containsKey(p.getComponentName())) {
13098                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13099                return;
13100            }
13101
13102            mProviders.put(p.getComponentName(), p);
13103            if (DEBUG_SHOW_INFO) {
13104                Log.v(TAG, "  "
13105                        + (p.info.nonLocalizedLabel != null
13106                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13107                Log.v(TAG, "    Class=" + p.info.name);
13108            }
13109            final int NI = p.intents.size();
13110            int j;
13111            for (j = 0; j < NI; j++) {
13112                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13113                if (DEBUG_SHOW_INFO) {
13114                    Log.v(TAG, "    IntentFilter:");
13115                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13116                }
13117                if (!intent.debugCheck()) {
13118                    Log.w(TAG, "==> For Provider " + p.info.name);
13119                }
13120                addFilter(intent);
13121            }
13122        }
13123
13124        public final void removeProvider(PackageParser.Provider p) {
13125            mProviders.remove(p.getComponentName());
13126            if (DEBUG_SHOW_INFO) {
13127                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13128                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13129                Log.v(TAG, "    Class=" + p.info.name);
13130            }
13131            final int NI = p.intents.size();
13132            int j;
13133            for (j = 0; j < NI; j++) {
13134                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13135                if (DEBUG_SHOW_INFO) {
13136                    Log.v(TAG, "    IntentFilter:");
13137                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13138                }
13139                removeFilter(intent);
13140            }
13141        }
13142
13143        @Override
13144        protected boolean allowFilterResult(
13145                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13146            ProviderInfo filterPi = filter.provider.info;
13147            for (int i = dest.size() - 1; i >= 0; i--) {
13148                ProviderInfo destPi = dest.get(i).providerInfo;
13149                if (destPi.name == filterPi.name
13150                        && destPi.packageName == filterPi.packageName) {
13151                    return false;
13152                }
13153            }
13154            return true;
13155        }
13156
13157        @Override
13158        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13159            return new PackageParser.ProviderIntentInfo[size];
13160        }
13161
13162        @Override
13163        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13164            if (!sUserManager.exists(userId))
13165                return true;
13166            PackageParser.Package p = filter.provider.owner;
13167            if (p != null) {
13168                PackageSetting ps = (PackageSetting) p.mExtras;
13169                if (ps != null) {
13170                    // System apps are never considered stopped for purposes of
13171                    // filtering, because there may be no way for the user to
13172                    // actually re-launch them.
13173                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13174                            && ps.getStopped(userId);
13175                }
13176            }
13177            return false;
13178        }
13179
13180        @Override
13181        protected boolean isPackageForFilter(String packageName,
13182                PackageParser.ProviderIntentInfo info) {
13183            return packageName.equals(info.provider.owner.packageName);
13184        }
13185
13186        @Override
13187        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13188                int match, int userId) {
13189            if (!sUserManager.exists(userId))
13190                return null;
13191            final PackageParser.ProviderIntentInfo info = filter;
13192            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13193                return null;
13194            }
13195            final PackageParser.Provider provider = info.provider;
13196            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13197            if (ps == null) {
13198                return null;
13199            }
13200            final PackageUserState userState = ps.readUserState(userId);
13201            final boolean matchVisibleToInstantApp =
13202                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13203            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13204            // throw out filters that aren't visible to instant applications
13205            if (matchVisibleToInstantApp
13206                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13207                return null;
13208            }
13209            // throw out instant application filters if we're not explicitly requesting them
13210            if (!isInstantApp && userState.instantApp) {
13211                return null;
13212            }
13213            // throw out instant application filters if updates are available; will trigger
13214            // instant application resolution
13215            if (userState.instantApp && ps.isUpdateAvailable()) {
13216                return null;
13217            }
13218            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13219                    userState, userId);
13220            if (pi == null) {
13221                return null;
13222            }
13223            final ResolveInfo res = new ResolveInfo();
13224            res.providerInfo = pi;
13225            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13226                res.filter = filter;
13227            }
13228            res.priority = info.getPriority();
13229            res.preferredOrder = provider.owner.mPreferredOrder;
13230            res.match = match;
13231            res.isDefault = info.hasDefault;
13232            res.labelRes = info.labelRes;
13233            res.nonLocalizedLabel = info.nonLocalizedLabel;
13234            res.icon = info.icon;
13235            res.system = res.providerInfo.applicationInfo.isSystemApp();
13236            return res;
13237        }
13238
13239        @Override
13240        protected void sortResults(List<ResolveInfo> results) {
13241            Collections.sort(results, mResolvePrioritySorter);
13242        }
13243
13244        @Override
13245        protected void dumpFilter(PrintWriter out, String prefix,
13246                PackageParser.ProviderIntentInfo filter) {
13247            out.print(prefix);
13248            out.print(
13249                    Integer.toHexString(System.identityHashCode(filter.provider)));
13250            out.print(' ');
13251            filter.provider.printComponentShortName(out);
13252            out.print(" filter ");
13253            out.println(Integer.toHexString(System.identityHashCode(filter)));
13254        }
13255
13256        @Override
13257        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13258            return filter.provider;
13259        }
13260
13261        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13262            PackageParser.Provider provider = (PackageParser.Provider)label;
13263            out.print(prefix); out.print(
13264                    Integer.toHexString(System.identityHashCode(provider)));
13265                    out.print(' ');
13266                    provider.printComponentShortName(out);
13267            if (count > 1) {
13268                out.print(" ("); out.print(count); out.print(" filters)");
13269            }
13270            out.println();
13271        }
13272
13273        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13274                = new ArrayMap<ComponentName, PackageParser.Provider>();
13275        private int mFlags;
13276    }
13277
13278    static final class InstantAppIntentResolver
13279            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13280            AuxiliaryResolveInfo.AuxiliaryFilter> {
13281        /**
13282         * The result that has the highest defined order. Ordering applies on a
13283         * per-package basis. Mapping is from package name to Pair of order and
13284         * EphemeralResolveInfo.
13285         * <p>
13286         * NOTE: This is implemented as a field variable for convenience and efficiency.
13287         * By having a field variable, we're able to track filter ordering as soon as
13288         * a non-zero order is defined. Otherwise, multiple loops across the result set
13289         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13290         * this needs to be contained entirely within {@link #filterResults}.
13291         */
13292        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13293
13294        @Override
13295        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13296            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13297        }
13298
13299        @Override
13300        protected boolean isPackageForFilter(String packageName,
13301                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13302            return true;
13303        }
13304
13305        @Override
13306        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13307                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13308            if (!sUserManager.exists(userId)) {
13309                return null;
13310            }
13311            final String packageName = responseObj.resolveInfo.getPackageName();
13312            final Integer order = responseObj.getOrder();
13313            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13314                    mOrderResult.get(packageName);
13315            // ordering is enabled and this item's order isn't high enough
13316            if (lastOrderResult != null && lastOrderResult.first >= order) {
13317                return null;
13318            }
13319            final InstantAppResolveInfo res = responseObj.resolveInfo;
13320            if (order > 0) {
13321                // non-zero order, enable ordering
13322                mOrderResult.put(packageName, new Pair<>(order, res));
13323            }
13324            return responseObj;
13325        }
13326
13327        @Override
13328        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13329            // only do work if ordering is enabled [most of the time it won't be]
13330            if (mOrderResult.size() == 0) {
13331                return;
13332            }
13333            int resultSize = results.size();
13334            for (int i = 0; i < resultSize; i++) {
13335                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13336                final String packageName = info.getPackageName();
13337                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13338                if (savedInfo == null) {
13339                    // package doesn't having ordering
13340                    continue;
13341                }
13342                if (savedInfo.second == info) {
13343                    // circled back to the highest ordered item; remove from order list
13344                    mOrderResult.remove(packageName);
13345                    if (mOrderResult.size() == 0) {
13346                        // no more ordered items
13347                        break;
13348                    }
13349                    continue;
13350                }
13351                // item has a worse order, remove it from the result list
13352                results.remove(i);
13353                resultSize--;
13354                i--;
13355            }
13356        }
13357    }
13358
13359    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13360            new Comparator<ResolveInfo>() {
13361        public int compare(ResolveInfo r1, ResolveInfo r2) {
13362            int v1 = r1.priority;
13363            int v2 = r2.priority;
13364            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13365            if (v1 != v2) {
13366                return (v1 > v2) ? -1 : 1;
13367            }
13368            v1 = r1.preferredOrder;
13369            v2 = r2.preferredOrder;
13370            if (v1 != v2) {
13371                return (v1 > v2) ? -1 : 1;
13372            }
13373            if (r1.isDefault != r2.isDefault) {
13374                return r1.isDefault ? -1 : 1;
13375            }
13376            v1 = r1.match;
13377            v2 = r2.match;
13378            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13379            if (v1 != v2) {
13380                return (v1 > v2) ? -1 : 1;
13381            }
13382            if (r1.system != r2.system) {
13383                return r1.system ? -1 : 1;
13384            }
13385            if (r1.activityInfo != null) {
13386                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13387            }
13388            if (r1.serviceInfo != null) {
13389                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13390            }
13391            if (r1.providerInfo != null) {
13392                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13393            }
13394            return 0;
13395        }
13396    };
13397
13398    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13399            new Comparator<ProviderInfo>() {
13400        public int compare(ProviderInfo p1, ProviderInfo p2) {
13401            final int v1 = p1.initOrder;
13402            final int v2 = p2.initOrder;
13403            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13404        }
13405    };
13406
13407    @Override
13408    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13409            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13410            final int[] userIds, int[] instantUserIds) {
13411        mHandler.post(new Runnable() {
13412            @Override
13413            public void run() {
13414                try {
13415                    final IActivityManager am = ActivityManager.getService();
13416                    if (am == null) return;
13417                    final int[] resolvedUserIds;
13418                    if (userIds == null) {
13419                        resolvedUserIds = am.getRunningUserIds();
13420                    } else {
13421                        resolvedUserIds = userIds;
13422                    }
13423                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13424                            resolvedUserIds, false);
13425                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13426                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13427                                instantUserIds, true);
13428                    }
13429                } catch (RemoteException ex) {
13430                }
13431            }
13432        });
13433    }
13434
13435    @Override
13436    public void notifyPackageAdded(String packageName) {
13437        final PackageListObserver[] observers;
13438        synchronized (mPackages) {
13439            if (mPackageListObservers.size() == 0) {
13440                return;
13441            }
13442            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13443        }
13444        for (int i = observers.length - 1; i >= 0; --i) {
13445            observers[i].onPackageAdded(packageName);
13446        }
13447    }
13448
13449    @Override
13450    public void notifyPackageRemoved(String packageName) {
13451        final PackageListObserver[] observers;
13452        synchronized (mPackages) {
13453            if (mPackageListObservers.size() == 0) {
13454                return;
13455            }
13456            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13457        }
13458        for (int i = observers.length - 1; i >= 0; --i) {
13459            observers[i].onPackageRemoved(packageName);
13460        }
13461    }
13462
13463    /**
13464     * Sends a broadcast for the given action.
13465     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13466     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13467     * the system and applications allowed to see instant applications to receive package
13468     * lifecycle events for instant applications.
13469     */
13470    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13471            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13472            int[] userIds, boolean isInstantApp)
13473                    throws RemoteException {
13474        for (int id : userIds) {
13475            final Intent intent = new Intent(action,
13476                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13477            final String[] requiredPermissions =
13478                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13479            if (extras != null) {
13480                intent.putExtras(extras);
13481            }
13482            if (targetPkg != null) {
13483                intent.setPackage(targetPkg);
13484            }
13485            // Modify the UID when posting to other users
13486            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13487            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13488                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13489                intent.putExtra(Intent.EXTRA_UID, uid);
13490            }
13491            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13492            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13493            if (DEBUG_BROADCASTS) {
13494                RuntimeException here = new RuntimeException("here");
13495                here.fillInStackTrace();
13496                Slog.d(TAG, "Sending to user " + id + ": "
13497                        + intent.toShortString(false, true, false, false)
13498                        + " " + intent.getExtras(), here);
13499            }
13500            am.broadcastIntent(null, intent, null, finishedReceiver,
13501                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13502                    null, finishedReceiver != null, false, id);
13503        }
13504    }
13505
13506    /**
13507     * Check if the external storage media is available. This is true if there
13508     * is a mounted external storage medium or if the external storage is
13509     * emulated.
13510     */
13511    private boolean isExternalMediaAvailable() {
13512        return mMediaMounted || Environment.isExternalStorageEmulated();
13513    }
13514
13515    @Override
13516    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13517        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13518            return null;
13519        }
13520        if (!isExternalMediaAvailable()) {
13521                // If the external storage is no longer mounted at this point,
13522                // the caller may not have been able to delete all of this
13523                // packages files and can not delete any more.  Bail.
13524            return null;
13525        }
13526        synchronized (mPackages) {
13527            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13528            if (lastPackage != null) {
13529                pkgs.remove(lastPackage);
13530            }
13531            if (pkgs.size() > 0) {
13532                return pkgs.get(0);
13533            }
13534        }
13535        return null;
13536    }
13537
13538    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13539        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13540                userId, andCode ? 1 : 0, packageName);
13541        if (mSystemReady) {
13542            msg.sendToTarget();
13543        } else {
13544            if (mPostSystemReadyMessages == null) {
13545                mPostSystemReadyMessages = new ArrayList<>();
13546            }
13547            mPostSystemReadyMessages.add(msg);
13548        }
13549    }
13550
13551    void startCleaningPackages() {
13552        // reader
13553        if (!isExternalMediaAvailable()) {
13554            return;
13555        }
13556        synchronized (mPackages) {
13557            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13558                return;
13559            }
13560        }
13561        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13562        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13563        IActivityManager am = ActivityManager.getService();
13564        if (am != null) {
13565            int dcsUid = -1;
13566            synchronized (mPackages) {
13567                if (!mDefaultContainerWhitelisted) {
13568                    mDefaultContainerWhitelisted = true;
13569                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13570                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13571                }
13572            }
13573            try {
13574                if (dcsUid > 0) {
13575                    am.backgroundWhitelistUid(dcsUid);
13576                }
13577                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13578                        UserHandle.USER_SYSTEM);
13579            } catch (RemoteException e) {
13580            }
13581        }
13582    }
13583
13584    /**
13585     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13586     * it is acting on behalf on an enterprise or the user).
13587     *
13588     * Note that the ordering of the conditionals in this method is important. The checks we perform
13589     * are as follows, in this order:
13590     *
13591     * 1) If the install is being performed by a system app, we can trust the app to have set the
13592     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13593     *    what it is.
13594     * 2) If the install is being performed by a device or profile owner app, the install reason
13595     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13596     *    set the install reason correctly. If the app targets an older SDK version where install
13597     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13598     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13599     * 3) In all other cases, the install is being performed by a regular app that is neither part
13600     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13601     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13602     *    set to enterprise policy and if so, change it to unknown instead.
13603     */
13604    private int fixUpInstallReason(String installerPackageName, int installerUid,
13605            int installReason) {
13606        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13607                == PERMISSION_GRANTED) {
13608            // If the install is being performed by a system app, we trust that app to have set the
13609            // install reason correctly.
13610            return installReason;
13611        }
13612
13613        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13614            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13615        if (dpm != null) {
13616            ComponentName owner = null;
13617            try {
13618                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13619                if (owner == null) {
13620                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13621                }
13622            } catch (RemoteException e) {
13623            }
13624            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13625                // If the install is being performed by a device or profile owner, the install
13626                // reason should be enterprise policy.
13627                return PackageManager.INSTALL_REASON_POLICY;
13628            }
13629        }
13630
13631        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13632            // If the install is being performed by a regular app (i.e. neither system app nor
13633            // device or profile owner), we have no reason to believe that the app is acting on
13634            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13635            // change it to unknown instead.
13636            return PackageManager.INSTALL_REASON_UNKNOWN;
13637        }
13638
13639        // If the install is being performed by a regular app and the install reason was set to any
13640        // value but enterprise policy, leave the install reason unchanged.
13641        return installReason;
13642    }
13643
13644    /**
13645     * Attempts to bind to the default container service explicitly instead of doing so lazily on
13646     * install commit.
13647     */
13648    void earlyBindToDefContainer() {
13649        mHandler.sendMessage(mHandler.obtainMessage(DEF_CONTAINER_BIND));
13650    }
13651
13652    void installStage(String packageName, File stagedDir,
13653            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13654            String installerPackageName, int installerUid, UserHandle user,
13655            PackageParser.SigningDetails signingDetails) {
13656        if (DEBUG_INSTANT) {
13657            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13658                Slog.d(TAG, "Ephemeral install of " + packageName);
13659            }
13660        }
13661        final VerificationInfo verificationInfo = new VerificationInfo(
13662                sessionParams.originatingUri, sessionParams.referrerUri,
13663                sessionParams.originatingUid, installerUid);
13664
13665        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13666
13667        final Message msg = mHandler.obtainMessage(INIT_COPY);
13668        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13669                sessionParams.installReason);
13670        final InstallParams params = new InstallParams(origin, null, observer,
13671                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13672                verificationInfo, user, sessionParams.abiOverride,
13673                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13674        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13675        msg.obj = params;
13676
13677        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13678                System.identityHashCode(msg.obj));
13679        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13680                System.identityHashCode(msg.obj));
13681
13682        mHandler.sendMessage(msg);
13683    }
13684
13685    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13686            int userId) {
13687        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13688        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13689        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13690        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13691        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13692                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13693
13694        // Send a session commit broadcast
13695        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13696        info.installReason = pkgSetting.getInstallReason(userId);
13697        info.appPackageName = packageName;
13698        sendSessionCommitBroadcast(info, userId);
13699    }
13700
13701    @Override
13702    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13703            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13704        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13705            return;
13706        }
13707        Bundle extras = new Bundle(1);
13708        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13709        final int uid = UserHandle.getUid(
13710                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13711        extras.putInt(Intent.EXTRA_UID, uid);
13712
13713        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13714                packageName, extras, 0, null, null, userIds, instantUserIds);
13715        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13716            mHandler.post(() -> {
13717                        for (int userId : userIds) {
13718                            sendBootCompletedBroadcastToSystemApp(
13719                                    packageName, includeStopped, userId);
13720                        }
13721                    }
13722            );
13723        }
13724    }
13725
13726    /**
13727     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13728     * automatically without needing an explicit launch.
13729     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13730     */
13731    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13732            int userId) {
13733        // If user is not running, the app didn't miss any broadcast
13734        if (!mUserManagerInternal.isUserRunning(userId)) {
13735            return;
13736        }
13737        final IActivityManager am = ActivityManager.getService();
13738        try {
13739            // Deliver LOCKED_BOOT_COMPLETED first
13740            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13741                    .setPackage(packageName);
13742            if (includeStopped) {
13743                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13744            }
13745            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13746            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13747                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13748
13749            // Deliver BOOT_COMPLETED only if user is unlocked
13750            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13751                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13752                if (includeStopped) {
13753                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13754                }
13755                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13756                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13757            }
13758        } catch (RemoteException e) {
13759            throw e.rethrowFromSystemServer();
13760        }
13761    }
13762
13763    @Override
13764    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13765            int userId) {
13766        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13767        PackageSetting pkgSetting;
13768        final int callingUid = Binder.getCallingUid();
13769        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13770                true /* requireFullPermission */, true /* checkShell */,
13771                "setApplicationHiddenSetting for user " + userId);
13772
13773        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13774            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13775            return false;
13776        }
13777
13778        long callingId = Binder.clearCallingIdentity();
13779        try {
13780            boolean sendAdded = false;
13781            boolean sendRemoved = false;
13782            // writer
13783            synchronized (mPackages) {
13784                pkgSetting = mSettings.mPackages.get(packageName);
13785                if (pkgSetting == null) {
13786                    return false;
13787                }
13788                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13789                    return false;
13790                }
13791                // Do not allow "android" is being disabled
13792                if ("android".equals(packageName)) {
13793                    Slog.w(TAG, "Cannot hide package: android");
13794                    return false;
13795                }
13796                // Cannot hide static shared libs as they are considered
13797                // a part of the using app (emulating static linking). Also
13798                // static libs are installed always on internal storage.
13799                PackageParser.Package pkg = mPackages.get(packageName);
13800                if (pkg != null && pkg.staticSharedLibName != null) {
13801                    Slog.w(TAG, "Cannot hide package: " + packageName
13802                            + " providing static shared library: "
13803                            + pkg.staticSharedLibName);
13804                    return false;
13805                }
13806                // Only allow protected packages to hide themselves.
13807                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13808                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13809                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13810                    return false;
13811                }
13812
13813                if (pkgSetting.getHidden(userId) != hidden) {
13814                    pkgSetting.setHidden(hidden, userId);
13815                    mSettings.writePackageRestrictionsLPr(userId);
13816                    if (hidden) {
13817                        sendRemoved = true;
13818                    } else {
13819                        sendAdded = true;
13820                    }
13821                }
13822            }
13823            if (sendAdded) {
13824                sendPackageAddedForUser(packageName, pkgSetting, userId);
13825                return true;
13826            }
13827            if (sendRemoved) {
13828                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13829                        "hiding pkg");
13830                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13831                return true;
13832            }
13833        } finally {
13834            Binder.restoreCallingIdentity(callingId);
13835        }
13836        return false;
13837    }
13838
13839    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13840            int userId) {
13841        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13842        info.removedPackage = packageName;
13843        info.installerPackageName = pkgSetting.installerPackageName;
13844        info.removedUsers = new int[] {userId};
13845        info.broadcastUsers = new int[] {userId};
13846        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13847        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13848    }
13849
13850    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13851            PersistableBundle launcherExtras) {
13852        if (pkgList.length > 0) {
13853            Bundle extras = new Bundle(1);
13854            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13855            if (launcherExtras != null) {
13856                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13857                        new Bundle(launcherExtras.deepCopy()));
13858            }
13859            sendPackageBroadcast(
13860                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13861                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13862                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13863                    new int[] {userId}, null);
13864        }
13865    }
13866
13867    /**
13868     * Returns true if application is not found or there was an error. Otherwise it returns
13869     * the hidden state of the package for the given user.
13870     */
13871    @Override
13872    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13873        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13874        final int callingUid = Binder.getCallingUid();
13875        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13876                true /* requireFullPermission */, false /* checkShell */,
13877                "getApplicationHidden for user " + userId);
13878        PackageSetting ps;
13879        long callingId = Binder.clearCallingIdentity();
13880        try {
13881            // writer
13882            synchronized (mPackages) {
13883                ps = mSettings.mPackages.get(packageName);
13884                if (ps == null) {
13885                    return true;
13886                }
13887                if (filterAppAccessLPr(ps, callingUid, userId)) {
13888                    return true;
13889                }
13890                return ps.getHidden(userId);
13891            }
13892        } finally {
13893            Binder.restoreCallingIdentity(callingId);
13894        }
13895    }
13896
13897    /**
13898     * @hide
13899     */
13900    @Override
13901    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13902            int installReason) {
13903        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13904                null);
13905        PackageSetting pkgSetting;
13906        final int callingUid = Binder.getCallingUid();
13907        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13908                true /* requireFullPermission */, true /* checkShell */,
13909                "installExistingPackage for user " + userId);
13910        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13911            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13912        }
13913
13914        long callingId = Binder.clearCallingIdentity();
13915        try {
13916            boolean installed = false;
13917            final boolean instantApp =
13918                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13919            final boolean fullApp =
13920                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13921
13922            // writer
13923            synchronized (mPackages) {
13924                pkgSetting = mSettings.mPackages.get(packageName);
13925                if (pkgSetting == null) {
13926                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13927                }
13928                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13929                    // only allow the existing package to be used if it's installed as a full
13930                    // application for at least one user
13931                    boolean installAllowed = false;
13932                    for (int checkUserId : sUserManager.getUserIds()) {
13933                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13934                        if (installAllowed) {
13935                            break;
13936                        }
13937                    }
13938                    if (!installAllowed) {
13939                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13940                    }
13941                }
13942                if (!pkgSetting.getInstalled(userId)) {
13943                    pkgSetting.setInstalled(true, userId);
13944                    pkgSetting.setHidden(false, userId);
13945                    pkgSetting.setInstallReason(installReason, userId);
13946                    mSettings.writePackageRestrictionsLPr(userId);
13947                    mSettings.writeKernelMappingLPr(pkgSetting);
13948                    installed = true;
13949                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13950                    // upgrade app from instant to full; we don't allow app downgrade
13951                    installed = true;
13952                }
13953                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13954            }
13955
13956            if (installed) {
13957                if (pkgSetting.pkg != null) {
13958                    synchronized (mInstallLock) {
13959                        // We don't need to freeze for a brand new install
13960                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13961                    }
13962                }
13963                sendPackageAddedForUser(packageName, pkgSetting, userId);
13964                synchronized (mPackages) {
13965                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13966                }
13967            }
13968        } finally {
13969            Binder.restoreCallingIdentity(callingId);
13970        }
13971
13972        return PackageManager.INSTALL_SUCCEEDED;
13973    }
13974
13975    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13976            boolean instantApp, boolean fullApp) {
13977        // no state specified; do nothing
13978        if (!instantApp && !fullApp) {
13979            return;
13980        }
13981        if (userId != UserHandle.USER_ALL) {
13982            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13983                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13984            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13985                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13986            }
13987        } else {
13988            for (int currentUserId : sUserManager.getUserIds()) {
13989                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13990                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13991                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13992                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13993                }
13994            }
13995        }
13996    }
13997
13998    boolean isUserRestricted(int userId, String restrictionKey) {
13999        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14000        if (restrictions.getBoolean(restrictionKey, false)) {
14001            Log.w(TAG, "User is restricted: " + restrictionKey);
14002            return true;
14003        }
14004        return false;
14005    }
14006
14007    @Override
14008    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14009            PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage,
14010            String callingPackage, int userId) {
14011        try {
14012            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
14013        } catch (SecurityException e) {
14014            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
14015                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
14016                            + Manifest.permission.MANAGE_USERS);
14017        }
14018        final int callingUid = Binder.getCallingUid();
14019        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14020                true /* requireFullPermission */, true /* checkShell */,
14021                "setPackagesSuspended for user " + userId);
14022        if (callingUid != Process.ROOT_UID &&
14023                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
14024            throw new IllegalArgumentException("callingPackage " + callingPackage + " does not"
14025                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
14026        }
14027
14028        if (ArrayUtils.isEmpty(packageNames)) {
14029            return packageNames;
14030        }
14031
14032        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14033        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14034        final long callingId = Binder.clearCallingIdentity();
14035        try {
14036            synchronized (mPackages) {
14037                for (int i = 0; i < packageNames.length; i++) {
14038                    final String packageName = packageNames[i];
14039                    if (callingPackage.equals(packageName)) {
14040                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14041                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14042                        unactionedPackages.add(packageName);
14043                        continue;
14044                    }
14045                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14046                    if (pkgSetting == null
14047                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14048                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14049                                + "\". Skipping suspending/un-suspending.");
14050                        unactionedPackages.add(packageName);
14051                        continue;
14052                    }
14053                    if (pkgSetting.getSuspended(userId) != suspended) {
14054                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14055                            unactionedPackages.add(packageName);
14056                            continue;
14057                        }
14058                        pkgSetting.setSuspended(suspended, callingPackage, dialogMessage, appExtras,
14059                                launcherExtras, userId);
14060                        changedPackagesList.add(packageName);
14061                    }
14062                }
14063            }
14064        } finally {
14065            Binder.restoreCallingIdentity(callingId);
14066        }
14067        if (!changedPackagesList.isEmpty()) {
14068            final String[] changedPackages = changedPackagesList.toArray(
14069                    new String[changedPackagesList.size()]);
14070            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14071            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14072            synchronized (mPackages) {
14073                scheduleWritePackageRestrictionsLocked(userId);
14074            }
14075        }
14076
14077        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14078    }
14079
14080    @Override
14081    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14082        final int callingUid = Binder.getCallingUid();
14083        if (getPackageUid(packageName, 0, userId) != callingUid) {
14084            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14085        }
14086        synchronized (mPackages) {
14087            final PackageSetting ps = mSettings.mPackages.get(packageName);
14088            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14089                throw new IllegalArgumentException("Unknown target package: " + packageName);
14090            }
14091            final PackageUserState packageUserState = ps.readUserState(userId);
14092            if (packageUserState.suspended) {
14093                return packageUserState.suspendedAppExtras;
14094            }
14095            return null;
14096        }
14097    }
14098
14099    @Override
14100    public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras,
14101            int userId) {
14102        final int callingUid = Binder.getCallingUid();
14103        mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14104        synchronized (mPackages) {
14105            final PackageSetting ps = mSettings.mPackages.get(packageName);
14106            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14107                throw new IllegalArgumentException("Unknown target package: " + packageName);
14108            }
14109            final PackageUserState packageUserState = ps.readUserState(userId);
14110            if (packageUserState.suspended) {
14111                packageUserState.suspendedAppExtras = appExtras;
14112                sendMyPackageSuspendedOrUnsuspended(new String[] {packageName}, true, appExtras,
14113                        userId);
14114            }
14115        }
14116    }
14117
14118    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14119            PersistableBundle appExtras, int userId) {
14120        final String action;
14121        final Bundle intentExtras = new Bundle();
14122        if (suspended) {
14123            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14124            if (appExtras != null) {
14125                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14126                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14127            }
14128        } else {
14129            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14130        }
14131        mHandler.post(new Runnable() {
14132            @Override
14133            public void run() {
14134                try {
14135                    final IActivityManager am = ActivityManager.getService();
14136                    if (am == null) {
14137                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14138                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14139                        return;
14140                    }
14141                    final int[] targetUserIds = new int[] {userId};
14142                    for (String packageName : affectedPackages) {
14143                        doSendBroadcast(am, action, null, intentExtras,
14144                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14145                                targetUserIds, false);
14146                    }
14147                } catch (RemoteException ex) {
14148                    // Shouldn't happen as AMS is in the same process.
14149                }
14150            }
14151        });
14152    }
14153
14154    @Override
14155    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14156        final int callingUid = Binder.getCallingUid();
14157        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14158                true /* requireFullPermission */, false /* checkShell */,
14159                "isPackageSuspendedForUser for user " + userId);
14160        if (getPackageUid(packageName, 0, userId) != callingUid) {
14161            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14162        }
14163        synchronized (mPackages) {
14164            final PackageSetting ps = mSettings.mPackages.get(packageName);
14165            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14166                throw new IllegalArgumentException("Unknown target package: " + packageName);
14167            }
14168            return ps.getSuspended(userId);
14169        }
14170    }
14171
14172    void onSuspendingPackageRemoved(String packageName, int userId) {
14173        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14174                : new int[] {userId};
14175        synchronized (mPackages) {
14176            for (PackageSetting ps : mSettings.mPackages.values()) {
14177                for (int user : userIds) {
14178                    final PackageUserState pus = ps.readUserState(user);
14179                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14180                        ps.setSuspended(false, null, null, null, null, user);
14181                    }
14182                }
14183            }
14184        }
14185    }
14186
14187    @GuardedBy("mPackages")
14188    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14189        if (isPackageDeviceAdmin(packageName, userId)) {
14190            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14191                    + "\": has an active device admin");
14192            return false;
14193        }
14194
14195        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14196        if (packageName.equals(activeLauncherPackageName)) {
14197            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14198                    + "\": contains the active launcher");
14199            return false;
14200        }
14201
14202        if (packageName.equals(mRequiredInstallerPackage)) {
14203            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14204                    + "\": required for package installation");
14205            return false;
14206        }
14207
14208        if (packageName.equals(mRequiredUninstallerPackage)) {
14209            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14210                    + "\": required for package uninstallation");
14211            return false;
14212        }
14213
14214        if (packageName.equals(mRequiredVerifierPackage)) {
14215            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14216                    + "\": required for package verification");
14217            return false;
14218        }
14219
14220        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14221            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14222                    + "\": is the default dialer");
14223            return false;
14224        }
14225
14226        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14227            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14228                    + "\": protected package");
14229            return false;
14230        }
14231
14232        // Cannot suspend static shared libs as they are considered
14233        // a part of the using app (emulating static linking). Also
14234        // static libs are installed always on internal storage.
14235        PackageParser.Package pkg = mPackages.get(packageName);
14236        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14237            Slog.w(TAG, "Cannot suspend package: " + packageName
14238                    + " providing static shared library: "
14239                    + pkg.staticSharedLibName);
14240            return false;
14241        }
14242
14243        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14244            Slog.w(TAG, "Cannot suspend package: " + packageName);
14245            return false;
14246        }
14247
14248        return true;
14249    }
14250
14251    private String getActiveLauncherPackageName(int userId) {
14252        Intent intent = new Intent(Intent.ACTION_MAIN);
14253        intent.addCategory(Intent.CATEGORY_HOME);
14254        ResolveInfo resolveInfo = resolveIntent(
14255                intent,
14256                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14257                PackageManager.MATCH_DEFAULT_ONLY,
14258                userId);
14259
14260        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14261    }
14262
14263    private String getDefaultDialerPackageName(int userId) {
14264        synchronized (mPackages) {
14265            return mSettings.getDefaultDialerPackageNameLPw(userId);
14266        }
14267    }
14268
14269    @Override
14270    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14271        mContext.enforceCallingOrSelfPermission(
14272                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14273                "Only package verification agents can verify applications");
14274
14275        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14276        final PackageVerificationResponse response = new PackageVerificationResponse(
14277                verificationCode, Binder.getCallingUid());
14278        msg.arg1 = id;
14279        msg.obj = response;
14280        mHandler.sendMessage(msg);
14281    }
14282
14283    @Override
14284    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14285            long millisecondsToDelay) {
14286        mContext.enforceCallingOrSelfPermission(
14287                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14288                "Only package verification agents can extend verification timeouts");
14289
14290        final PackageVerificationState state = mPendingVerification.get(id);
14291        final PackageVerificationResponse response = new PackageVerificationResponse(
14292                verificationCodeAtTimeout, Binder.getCallingUid());
14293
14294        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14295            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14296        }
14297        if (millisecondsToDelay < 0) {
14298            millisecondsToDelay = 0;
14299        }
14300        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14301                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14302            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14303        }
14304
14305        if ((state != null) && !state.timeoutExtended()) {
14306            state.extendTimeout();
14307
14308            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14309            msg.arg1 = id;
14310            msg.obj = response;
14311            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14312        }
14313    }
14314
14315    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14316            int verificationCode, UserHandle user) {
14317        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14318        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14319        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14320        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14321        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14322
14323        mContext.sendBroadcastAsUser(intent, user,
14324                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14325    }
14326
14327    private ComponentName matchComponentForVerifier(String packageName,
14328            List<ResolveInfo> receivers) {
14329        ActivityInfo targetReceiver = null;
14330
14331        final int NR = receivers.size();
14332        for (int i = 0; i < NR; i++) {
14333            final ResolveInfo info = receivers.get(i);
14334            if (info.activityInfo == null) {
14335                continue;
14336            }
14337
14338            if (packageName.equals(info.activityInfo.packageName)) {
14339                targetReceiver = info.activityInfo;
14340                break;
14341            }
14342        }
14343
14344        if (targetReceiver == null) {
14345            return null;
14346        }
14347
14348        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14349    }
14350
14351    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14352            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14353        if (pkgInfo.verifiers.length == 0) {
14354            return null;
14355        }
14356
14357        final int N = pkgInfo.verifiers.length;
14358        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14359        for (int i = 0; i < N; i++) {
14360            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14361
14362            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14363                    receivers);
14364            if (comp == null) {
14365                continue;
14366            }
14367
14368            final int verifierUid = getUidForVerifier(verifierInfo);
14369            if (verifierUid == -1) {
14370                continue;
14371            }
14372
14373            if (DEBUG_VERIFY) {
14374                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14375                        + " with the correct signature");
14376            }
14377            sufficientVerifiers.add(comp);
14378            verificationState.addSufficientVerifier(verifierUid);
14379        }
14380
14381        return sufficientVerifiers;
14382    }
14383
14384    private int getUidForVerifier(VerifierInfo verifierInfo) {
14385        synchronized (mPackages) {
14386            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14387            if (pkg == null) {
14388                return -1;
14389            } else if (pkg.mSigningDetails.signatures.length != 1) {
14390                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14391                        + " has more than one signature; ignoring");
14392                return -1;
14393            }
14394
14395            /*
14396             * If the public key of the package's signature does not match
14397             * our expected public key, then this is a different package and
14398             * we should skip.
14399             */
14400
14401            final byte[] expectedPublicKey;
14402            try {
14403                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14404                final PublicKey publicKey = verifierSig.getPublicKey();
14405                expectedPublicKey = publicKey.getEncoded();
14406            } catch (CertificateException e) {
14407                return -1;
14408            }
14409
14410            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14411
14412            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14413                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14414                        + " does not have the expected public key; ignoring");
14415                return -1;
14416            }
14417
14418            return pkg.applicationInfo.uid;
14419        }
14420    }
14421
14422    @Override
14423    public void finishPackageInstall(int token, boolean didLaunch) {
14424        enforceSystemOrRoot("Only the system is allowed to finish installs");
14425
14426        if (DEBUG_INSTALL) {
14427            Slog.v(TAG, "BM finishing package install for " + token);
14428        }
14429        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14430
14431        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14432        mHandler.sendMessage(msg);
14433    }
14434
14435    /**
14436     * Get the verification agent timeout.  Used for both the APK verifier and the
14437     * intent filter verifier.
14438     *
14439     * @return verification timeout in milliseconds
14440     */
14441    private long getVerificationTimeout() {
14442        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14443                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14444                DEFAULT_VERIFICATION_TIMEOUT);
14445    }
14446
14447    /**
14448     * Get the default verification agent response code.
14449     *
14450     * @return default verification response code
14451     */
14452    private int getDefaultVerificationResponse(UserHandle user) {
14453        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14454            return PackageManager.VERIFICATION_REJECT;
14455        }
14456        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14457                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14458                DEFAULT_VERIFICATION_RESPONSE);
14459    }
14460
14461    /**
14462     * Check whether or not package verification has been enabled.
14463     *
14464     * @return true if verification should be performed
14465     */
14466    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14467        if (!DEFAULT_VERIFY_ENABLE) {
14468            return false;
14469        }
14470
14471        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14472
14473        // Check if installing from ADB
14474        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14475            // Do not run verification in a test harness environment
14476            if (ActivityManager.isRunningInTestHarness()) {
14477                return false;
14478            }
14479            if (ensureVerifyAppsEnabled) {
14480                return true;
14481            }
14482            // Check if the developer does not want package verification for ADB installs
14483            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14484                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14485                return false;
14486            }
14487        } else {
14488            // only when not installed from ADB, skip verification for instant apps when
14489            // the installer and verifier are the same.
14490            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14491                if (mInstantAppInstallerActivity != null
14492                        && mInstantAppInstallerActivity.packageName.equals(
14493                                mRequiredVerifierPackage)) {
14494                    try {
14495                        mContext.getSystemService(AppOpsManager.class)
14496                                .checkPackage(installerUid, mRequiredVerifierPackage);
14497                        if (DEBUG_VERIFY) {
14498                            Slog.i(TAG, "disable verification for instant app");
14499                        }
14500                        return false;
14501                    } catch (SecurityException ignore) { }
14502                }
14503            }
14504        }
14505
14506        if (ensureVerifyAppsEnabled) {
14507            return true;
14508        }
14509
14510        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14511                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14512    }
14513
14514    @Override
14515    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14516            throws RemoteException {
14517        mContext.enforceCallingOrSelfPermission(
14518                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14519                "Only intentfilter verification agents can verify applications");
14520
14521        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14522        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14523                Binder.getCallingUid(), verificationCode, failedDomains);
14524        msg.arg1 = id;
14525        msg.obj = response;
14526        mHandler.sendMessage(msg);
14527    }
14528
14529    @Override
14530    public int getIntentVerificationStatus(String packageName, int userId) {
14531        final int callingUid = Binder.getCallingUid();
14532        if (UserHandle.getUserId(callingUid) != userId) {
14533            mContext.enforceCallingOrSelfPermission(
14534                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14535                    "getIntentVerificationStatus" + userId);
14536        }
14537        if (getInstantAppPackageName(callingUid) != null) {
14538            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14539        }
14540        synchronized (mPackages) {
14541            final PackageSetting ps = mSettings.mPackages.get(packageName);
14542            if (ps == null
14543                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14544                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14545            }
14546            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14547        }
14548    }
14549
14550    @Override
14551    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14552        mContext.enforceCallingOrSelfPermission(
14553                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14554
14555        boolean result = false;
14556        synchronized (mPackages) {
14557            final PackageSetting ps = mSettings.mPackages.get(packageName);
14558            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14559                return false;
14560            }
14561            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14562        }
14563        if (result) {
14564            scheduleWritePackageRestrictionsLocked(userId);
14565        }
14566        return result;
14567    }
14568
14569    @Override
14570    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14571            String packageName) {
14572        final int callingUid = Binder.getCallingUid();
14573        if (getInstantAppPackageName(callingUid) != null) {
14574            return ParceledListSlice.emptyList();
14575        }
14576        synchronized (mPackages) {
14577            final PackageSetting ps = mSettings.mPackages.get(packageName);
14578            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14579                return ParceledListSlice.emptyList();
14580            }
14581            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14582        }
14583    }
14584
14585    @Override
14586    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14587        if (TextUtils.isEmpty(packageName)) {
14588            return ParceledListSlice.emptyList();
14589        }
14590        final int callingUid = Binder.getCallingUid();
14591        final int callingUserId = UserHandle.getUserId(callingUid);
14592        synchronized (mPackages) {
14593            PackageParser.Package pkg = mPackages.get(packageName);
14594            if (pkg == null || pkg.activities == null) {
14595                return ParceledListSlice.emptyList();
14596            }
14597            if (pkg.mExtras == null) {
14598                return ParceledListSlice.emptyList();
14599            }
14600            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14601            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14602                return ParceledListSlice.emptyList();
14603            }
14604            final int count = pkg.activities.size();
14605            ArrayList<IntentFilter> result = new ArrayList<>();
14606            for (int n=0; n<count; n++) {
14607                PackageParser.Activity activity = pkg.activities.get(n);
14608                if (activity.intents != null && activity.intents.size() > 0) {
14609                    result.addAll(activity.intents);
14610                }
14611            }
14612            return new ParceledListSlice<>(result);
14613        }
14614    }
14615
14616    @Override
14617    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14618        mContext.enforceCallingOrSelfPermission(
14619                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14620        if (UserHandle.getCallingUserId() != userId) {
14621            mContext.enforceCallingOrSelfPermission(
14622                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14623        }
14624
14625        synchronized (mPackages) {
14626            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14627            if (packageName != null) {
14628                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14629                        packageName, userId);
14630            }
14631            return result;
14632        }
14633    }
14634
14635    @Override
14636    public String getDefaultBrowserPackageName(int userId) {
14637        if (UserHandle.getCallingUserId() != userId) {
14638            mContext.enforceCallingOrSelfPermission(
14639                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14640        }
14641        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14642            return null;
14643        }
14644        synchronized (mPackages) {
14645            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14646        }
14647    }
14648
14649    /**
14650     * Get the "allow unknown sources" setting.
14651     *
14652     * @return the current "allow unknown sources" setting
14653     */
14654    private int getUnknownSourcesSettings() {
14655        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14656                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14657                -1);
14658    }
14659
14660    @Override
14661    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14662        final int callingUid = Binder.getCallingUid();
14663        if (getInstantAppPackageName(callingUid) != null) {
14664            return;
14665        }
14666        // writer
14667        synchronized (mPackages) {
14668            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14669            if (targetPackageSetting == null
14670                    || filterAppAccessLPr(
14671                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14672                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14673            }
14674
14675            PackageSetting installerPackageSetting;
14676            if (installerPackageName != null) {
14677                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14678                if (installerPackageSetting == null) {
14679                    throw new IllegalArgumentException("Unknown installer package: "
14680                            + installerPackageName);
14681                }
14682            } else {
14683                installerPackageSetting = null;
14684            }
14685
14686            Signature[] callerSignature;
14687            Object obj = mSettings.getUserIdLPr(callingUid);
14688            if (obj != null) {
14689                if (obj instanceof SharedUserSetting) {
14690                    callerSignature =
14691                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14692                } else if (obj instanceof PackageSetting) {
14693                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14694                } else {
14695                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14696                }
14697            } else {
14698                throw new SecurityException("Unknown calling UID: " + callingUid);
14699            }
14700
14701            // Verify: can't set installerPackageName to a package that is
14702            // not signed with the same cert as the caller.
14703            if (installerPackageSetting != null) {
14704                if (compareSignatures(callerSignature,
14705                        installerPackageSetting.signatures.mSigningDetails.signatures)
14706                        != PackageManager.SIGNATURE_MATCH) {
14707                    throw new SecurityException(
14708                            "Caller does not have same cert as new installer package "
14709                            + installerPackageName);
14710                }
14711            }
14712
14713            // Verify: if target already has an installer package, it must
14714            // be signed with the same cert as the caller.
14715            if (targetPackageSetting.installerPackageName != null) {
14716                PackageSetting setting = mSettings.mPackages.get(
14717                        targetPackageSetting.installerPackageName);
14718                // If the currently set package isn't valid, then it's always
14719                // okay to change it.
14720                if (setting != null) {
14721                    if (compareSignatures(callerSignature,
14722                            setting.signatures.mSigningDetails.signatures)
14723                            != PackageManager.SIGNATURE_MATCH) {
14724                        throw new SecurityException(
14725                                "Caller does not have same cert as old installer package "
14726                                + targetPackageSetting.installerPackageName);
14727                    }
14728                }
14729            }
14730
14731            // Okay!
14732            targetPackageSetting.installerPackageName = installerPackageName;
14733            if (installerPackageName != null) {
14734                mSettings.mInstallerPackages.add(installerPackageName);
14735            }
14736            scheduleWriteSettingsLocked();
14737        }
14738    }
14739
14740    @Override
14741    public void setApplicationCategoryHint(String packageName, int categoryHint,
14742            String callerPackageName) {
14743        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14744            throw new SecurityException("Instant applications don't have access to this method");
14745        }
14746        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14747                callerPackageName);
14748        synchronized (mPackages) {
14749            PackageSetting ps = mSettings.mPackages.get(packageName);
14750            if (ps == null) {
14751                throw new IllegalArgumentException("Unknown target package " + packageName);
14752            }
14753            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14754                throw new IllegalArgumentException("Unknown target package " + packageName);
14755            }
14756            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14757                throw new IllegalArgumentException("Calling package " + callerPackageName
14758                        + " is not installer for " + packageName);
14759            }
14760
14761            if (ps.categoryHint != categoryHint) {
14762                ps.categoryHint = categoryHint;
14763                scheduleWriteSettingsLocked();
14764            }
14765        }
14766    }
14767
14768    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14769        // Queue up an async operation since the package installation may take a little while.
14770        mHandler.post(new Runnable() {
14771            public void run() {
14772                mHandler.removeCallbacks(this);
14773                 // Result object to be returned
14774                PackageInstalledInfo res = new PackageInstalledInfo();
14775                res.setReturnCode(currentStatus);
14776                res.uid = -1;
14777                res.pkg = null;
14778                res.removedInfo = null;
14779                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14780                    args.doPreInstall(res.returnCode);
14781                    synchronized (mInstallLock) {
14782                        installPackageTracedLI(args, res);
14783                    }
14784                    args.doPostInstall(res.returnCode, res.uid);
14785                }
14786
14787                // A restore should be performed at this point if (a) the install
14788                // succeeded, (b) the operation is not an update, and (c) the new
14789                // package has not opted out of backup participation.
14790                final boolean update = res.removedInfo != null
14791                        && res.removedInfo.removedPackage != null;
14792                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14793                boolean doRestore = !update
14794                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14795
14796                // Set up the post-install work request bookkeeping.  This will be used
14797                // and cleaned up by the post-install event handling regardless of whether
14798                // there's a restore pass performed.  Token values are >= 1.
14799                int token;
14800                if (mNextInstallToken < 0) mNextInstallToken = 1;
14801                token = mNextInstallToken++;
14802
14803                PostInstallData data = new PostInstallData(args, res);
14804                mRunningInstalls.put(token, data);
14805                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14806
14807                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14808                    // Pass responsibility to the Backup Manager.  It will perform a
14809                    // restore if appropriate, then pass responsibility back to the
14810                    // Package Manager to run the post-install observer callbacks
14811                    // and broadcasts.
14812                    IBackupManager bm = IBackupManager.Stub.asInterface(
14813                            ServiceManager.getService(Context.BACKUP_SERVICE));
14814                    if (bm != null) {
14815                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14816                                + " to BM for possible restore");
14817                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14818                        try {
14819                            // TODO: http://b/22388012
14820                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14821                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14822                            } else {
14823                                doRestore = false;
14824                            }
14825                        } catch (RemoteException e) {
14826                            // can't happen; the backup manager is local
14827                        } catch (Exception e) {
14828                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14829                            doRestore = false;
14830                        }
14831                    } else {
14832                        Slog.e(TAG, "Backup Manager not found!");
14833                        doRestore = false;
14834                    }
14835                }
14836
14837                if (!doRestore) {
14838                    // No restore possible, or the Backup Manager was mysteriously not
14839                    // available -- just fire the post-install work request directly.
14840                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14841
14842                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14843
14844                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14845                    mHandler.sendMessage(msg);
14846                }
14847            }
14848        });
14849    }
14850
14851    /**
14852     * Callback from PackageSettings whenever an app is first transitioned out of the
14853     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14854     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14855     * here whether the app is the target of an ongoing install, and only send the
14856     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14857     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14858     * handling.
14859     */
14860    void notifyFirstLaunch(final String packageName, final String installerPackage,
14861            final int userId) {
14862        // Serialize this with the rest of the install-process message chain.  In the
14863        // restore-at-install case, this Runnable will necessarily run before the
14864        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14865        // are coherent.  In the non-restore case, the app has already completed install
14866        // and been launched through some other means, so it is not in a problematic
14867        // state for observers to see the FIRST_LAUNCH signal.
14868        mHandler.post(new Runnable() {
14869            @Override
14870            public void run() {
14871                for (int i = 0; i < mRunningInstalls.size(); i++) {
14872                    final PostInstallData data = mRunningInstalls.valueAt(i);
14873                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14874                        continue;
14875                    }
14876                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14877                        // right package; but is it for the right user?
14878                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14879                            if (userId == data.res.newUsers[uIndex]) {
14880                                if (DEBUG_BACKUP) {
14881                                    Slog.i(TAG, "Package " + packageName
14882                                            + " being restored so deferring FIRST_LAUNCH");
14883                                }
14884                                return;
14885                            }
14886                        }
14887                    }
14888                }
14889                // didn't find it, so not being restored
14890                if (DEBUG_BACKUP) {
14891                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14892                }
14893                final boolean isInstantApp = isInstantApp(packageName, userId);
14894                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14895                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14896                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14897            }
14898        });
14899    }
14900
14901    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14902            int[] userIds, int[] instantUserIds) {
14903        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14904                installerPkg, null, userIds, instantUserIds);
14905    }
14906
14907    private abstract class HandlerParams {
14908        private static final int MAX_RETRIES = 4;
14909
14910        /**
14911         * Number of times startCopy() has been attempted and had a non-fatal
14912         * error.
14913         */
14914        private int mRetries = 0;
14915
14916        /** User handle for the user requesting the information or installation. */
14917        private final UserHandle mUser;
14918        String traceMethod;
14919        int traceCookie;
14920
14921        HandlerParams(UserHandle user) {
14922            mUser = user;
14923        }
14924
14925        UserHandle getUser() {
14926            return mUser;
14927        }
14928
14929        HandlerParams setTraceMethod(String traceMethod) {
14930            this.traceMethod = traceMethod;
14931            return this;
14932        }
14933
14934        HandlerParams setTraceCookie(int traceCookie) {
14935            this.traceCookie = traceCookie;
14936            return this;
14937        }
14938
14939        final boolean startCopy() {
14940            boolean res;
14941            try {
14942                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14943
14944                if (++mRetries > MAX_RETRIES) {
14945                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14946                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14947                    handleServiceError();
14948                    return false;
14949                } else {
14950                    handleStartCopy();
14951                    res = true;
14952                }
14953            } catch (RemoteException e) {
14954                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14955                mHandler.sendEmptyMessage(MCS_RECONNECT);
14956                res = false;
14957            }
14958            handleReturnCode();
14959            return res;
14960        }
14961
14962        final void serviceError() {
14963            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14964            handleServiceError();
14965            handleReturnCode();
14966        }
14967
14968        abstract void handleStartCopy() throws RemoteException;
14969        abstract void handleServiceError();
14970        abstract void handleReturnCode();
14971    }
14972
14973    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14974        for (File path : paths) {
14975            try {
14976                mcs.clearDirectory(path.getAbsolutePath());
14977            } catch (RemoteException e) {
14978            }
14979        }
14980    }
14981
14982    static class OriginInfo {
14983        /**
14984         * Location where install is coming from, before it has been
14985         * copied/renamed into place. This could be a single monolithic APK
14986         * file, or a cluster directory. This location may be untrusted.
14987         */
14988        final File file;
14989
14990        /**
14991         * Flag indicating that {@link #file} or {@link #cid} has already been
14992         * staged, meaning downstream users don't need to defensively copy the
14993         * contents.
14994         */
14995        final boolean staged;
14996
14997        /**
14998         * Flag indicating that {@link #file} or {@link #cid} is an already
14999         * installed app that is being moved.
15000         */
15001        final boolean existing;
15002
15003        final String resolvedPath;
15004        final File resolvedFile;
15005
15006        static OriginInfo fromNothing() {
15007            return new OriginInfo(null, false, false);
15008        }
15009
15010        static OriginInfo fromUntrustedFile(File file) {
15011            return new OriginInfo(file, false, false);
15012        }
15013
15014        static OriginInfo fromExistingFile(File file) {
15015            return new OriginInfo(file, false, true);
15016        }
15017
15018        static OriginInfo fromStagedFile(File file) {
15019            return new OriginInfo(file, true, false);
15020        }
15021
15022        private OriginInfo(File file, boolean staged, boolean existing) {
15023            this.file = file;
15024            this.staged = staged;
15025            this.existing = existing;
15026
15027            if (file != null) {
15028                resolvedPath = file.getAbsolutePath();
15029                resolvedFile = file;
15030            } else {
15031                resolvedPath = null;
15032                resolvedFile = null;
15033            }
15034        }
15035    }
15036
15037    static class MoveInfo {
15038        final int moveId;
15039        final String fromUuid;
15040        final String toUuid;
15041        final String packageName;
15042        final String dataAppName;
15043        final int appId;
15044        final String seinfo;
15045        final int targetSdkVersion;
15046
15047        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15048                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15049            this.moveId = moveId;
15050            this.fromUuid = fromUuid;
15051            this.toUuid = toUuid;
15052            this.packageName = packageName;
15053            this.dataAppName = dataAppName;
15054            this.appId = appId;
15055            this.seinfo = seinfo;
15056            this.targetSdkVersion = targetSdkVersion;
15057        }
15058    }
15059
15060    static class VerificationInfo {
15061        /** A constant used to indicate that a uid value is not present. */
15062        public static final int NO_UID = -1;
15063
15064        /** URI referencing where the package was downloaded from. */
15065        final Uri originatingUri;
15066
15067        /** HTTP referrer URI associated with the originatingURI. */
15068        final Uri referrer;
15069
15070        /** UID of the application that the install request originated from. */
15071        final int originatingUid;
15072
15073        /** UID of application requesting the install */
15074        final int installerUid;
15075
15076        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15077            this.originatingUri = originatingUri;
15078            this.referrer = referrer;
15079            this.originatingUid = originatingUid;
15080            this.installerUid = installerUid;
15081        }
15082    }
15083
15084    class InstallParams extends HandlerParams {
15085        final OriginInfo origin;
15086        final MoveInfo move;
15087        final IPackageInstallObserver2 observer;
15088        int installFlags;
15089        final String installerPackageName;
15090        final String volumeUuid;
15091        private InstallArgs mArgs;
15092        private int mRet;
15093        final String packageAbiOverride;
15094        final String[] grantedRuntimePermissions;
15095        final VerificationInfo verificationInfo;
15096        final PackageParser.SigningDetails signingDetails;
15097        final int installReason;
15098
15099        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15100                int installFlags, String installerPackageName, String volumeUuid,
15101                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15102                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15103            super(user);
15104            this.origin = origin;
15105            this.move = move;
15106            this.observer = observer;
15107            this.installFlags = installFlags;
15108            this.installerPackageName = installerPackageName;
15109            this.volumeUuid = volumeUuid;
15110            this.verificationInfo = verificationInfo;
15111            this.packageAbiOverride = packageAbiOverride;
15112            this.grantedRuntimePermissions = grantedPermissions;
15113            this.signingDetails = signingDetails;
15114            this.installReason = installReason;
15115        }
15116
15117        @Override
15118        public String toString() {
15119            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15120                    + " file=" + origin.file + "}";
15121        }
15122
15123        private int installLocationPolicy(PackageInfoLite pkgLite) {
15124            String packageName = pkgLite.packageName;
15125            int installLocation = pkgLite.installLocation;
15126            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15127            // reader
15128            synchronized (mPackages) {
15129                // Currently installed package which the new package is attempting to replace or
15130                // null if no such package is installed.
15131                PackageParser.Package installedPkg = mPackages.get(packageName);
15132                // Package which currently owns the data which the new package will own if installed.
15133                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15134                // will be null whereas dataOwnerPkg will contain information about the package
15135                // which was uninstalled while keeping its data.
15136                PackageParser.Package dataOwnerPkg = installedPkg;
15137                if (dataOwnerPkg  == null) {
15138                    PackageSetting ps = mSettings.mPackages.get(packageName);
15139                    if (ps != null) {
15140                        dataOwnerPkg = ps.pkg;
15141                    }
15142                }
15143
15144                if (dataOwnerPkg != null) {
15145                    // If installed, the package will get access to data left on the device by its
15146                    // predecessor. As a security measure, this is permited only if this is not a
15147                    // version downgrade or if the predecessor package is marked as debuggable and
15148                    // a downgrade is explicitly requested.
15149                    //
15150                    // On debuggable platform builds, downgrades are permitted even for
15151                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15152                    // not offer security guarantees and thus it's OK to disable some security
15153                    // mechanisms to make debugging/testing easier on those builds. However, even on
15154                    // debuggable builds downgrades of packages are permitted only if requested via
15155                    // installFlags. This is because we aim to keep the behavior of debuggable
15156                    // platform builds as close as possible to the behavior of non-debuggable
15157                    // platform builds.
15158                    final boolean downgradeRequested =
15159                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15160                    final boolean packageDebuggable =
15161                                (dataOwnerPkg.applicationInfo.flags
15162                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15163                    final boolean downgradePermitted =
15164                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15165                    if (!downgradePermitted) {
15166                        try {
15167                            checkDowngrade(dataOwnerPkg, pkgLite);
15168                        } catch (PackageManagerException e) {
15169                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15170                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15171                        }
15172                    }
15173                }
15174
15175                if (installedPkg != null) {
15176                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15177                        // Check for updated system application.
15178                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15179                            if (onSd) {
15180                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15181                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15182                            }
15183                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15184                        } else {
15185                            if (onSd) {
15186                                // Install flag overrides everything.
15187                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15188                            }
15189                            // If current upgrade specifies particular preference
15190                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15191                                // Application explicitly specified internal.
15192                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15193                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15194                                // App explictly prefers external. Let policy decide
15195                            } else {
15196                                // Prefer previous location
15197                                if (isExternal(installedPkg)) {
15198                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15199                                }
15200                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15201                            }
15202                        }
15203                    } else {
15204                        // Invalid install. Return error code
15205                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15206                    }
15207                }
15208            }
15209            // All the special cases have been taken care of.
15210            // Return result based on recommended install location.
15211            if (onSd) {
15212                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15213            }
15214            return pkgLite.recommendedInstallLocation;
15215        }
15216
15217        /*
15218         * Invoke remote method to get package information and install
15219         * location values. Override install location based on default
15220         * policy if needed and then create install arguments based
15221         * on the install location.
15222         */
15223        public void handleStartCopy() throws RemoteException {
15224            int ret = PackageManager.INSTALL_SUCCEEDED;
15225
15226            // If we're already staged, we've firmly committed to an install location
15227            if (origin.staged) {
15228                if (origin.file != null) {
15229                    installFlags |= PackageManager.INSTALL_INTERNAL;
15230                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15231                } else {
15232                    throw new IllegalStateException("Invalid stage location");
15233                }
15234            }
15235
15236            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15237            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15238            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15239            PackageInfoLite pkgLite = null;
15240
15241            if (onInt && onSd) {
15242                // Check if both bits are set.
15243                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15244                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15245            } else if (onSd && ephemeral) {
15246                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15247                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15248            } else {
15249                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15250                        packageAbiOverride);
15251
15252                if (DEBUG_INSTANT && ephemeral) {
15253                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15254                }
15255
15256                /*
15257                 * If we have too little free space, try to free cache
15258                 * before giving up.
15259                 */
15260                if (!origin.staged && pkgLite.recommendedInstallLocation
15261                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15262                    // TODO: focus freeing disk space on the target device
15263                    final StorageManager storage = StorageManager.from(mContext);
15264                    final long lowThreshold = storage.getStorageLowBytes(
15265                            Environment.getDataDirectory());
15266
15267                    final long sizeBytes = mContainerService.calculateInstalledSize(
15268                            origin.resolvedPath, packageAbiOverride);
15269
15270                    try {
15271                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15272                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15273                                installFlags, packageAbiOverride);
15274                    } catch (InstallerException e) {
15275                        Slog.w(TAG, "Failed to free cache", e);
15276                    }
15277
15278                    /*
15279                     * The cache free must have deleted the file we
15280                     * downloaded to install.
15281                     *
15282                     * TODO: fix the "freeCache" call to not delete
15283                     *       the file we care about.
15284                     */
15285                    if (pkgLite.recommendedInstallLocation
15286                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15287                        pkgLite.recommendedInstallLocation
15288                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15289                    }
15290                }
15291            }
15292
15293            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15294                int loc = pkgLite.recommendedInstallLocation;
15295                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15296                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15297                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15298                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15299                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15300                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15301                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15302                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15303                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15304                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15305                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15306                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15307                } else {
15308                    // Override with defaults if needed.
15309                    loc = installLocationPolicy(pkgLite);
15310                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15311                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15312                    } else if (!onSd && !onInt) {
15313                        // Override install location with flags
15314                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15315                            // Set the flag to install on external media.
15316                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15317                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15318                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15319                            if (DEBUG_INSTANT) {
15320                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15321                            }
15322                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15323                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15324                                    |PackageManager.INSTALL_INTERNAL);
15325                        } else {
15326                            // Make sure the flag for installing on external
15327                            // media is unset
15328                            installFlags |= PackageManager.INSTALL_INTERNAL;
15329                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15330                        }
15331                    }
15332                }
15333            }
15334
15335            final InstallArgs args = createInstallArgs(this);
15336            mArgs = args;
15337
15338            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15339                // TODO: http://b/22976637
15340                // Apps installed for "all" users use the device owner to verify the app
15341                UserHandle verifierUser = getUser();
15342                if (verifierUser == UserHandle.ALL) {
15343                    verifierUser = UserHandle.SYSTEM;
15344                }
15345
15346                /*
15347                 * Determine if we have any installed package verifiers. If we
15348                 * do, then we'll defer to them to verify the packages.
15349                 */
15350                final int requiredUid = mRequiredVerifierPackage == null ? -1
15351                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15352                                verifierUser.getIdentifier());
15353                final int installerUid =
15354                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15355                if (!origin.existing && requiredUid != -1
15356                        && isVerificationEnabled(
15357                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15358                    final Intent verification = new Intent(
15359                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15360                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15361                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15362                            PACKAGE_MIME_TYPE);
15363                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15364
15365                    // Query all live verifiers based on current user state
15366                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15367                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15368                            false /*allowDynamicSplits*/);
15369
15370                    if (DEBUG_VERIFY) {
15371                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15372                                + verification.toString() + " with " + pkgLite.verifiers.length
15373                                + " optional verifiers");
15374                    }
15375
15376                    final int verificationId = mPendingVerificationToken++;
15377
15378                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15379
15380                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15381                            installerPackageName);
15382
15383                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15384                            installFlags);
15385
15386                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15387                            pkgLite.packageName);
15388
15389                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15390                            pkgLite.versionCode);
15391
15392                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15393                            pkgLite.getLongVersionCode());
15394
15395                    if (verificationInfo != null) {
15396                        if (verificationInfo.originatingUri != null) {
15397                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15398                                    verificationInfo.originatingUri);
15399                        }
15400                        if (verificationInfo.referrer != null) {
15401                            verification.putExtra(Intent.EXTRA_REFERRER,
15402                                    verificationInfo.referrer);
15403                        }
15404                        if (verificationInfo.originatingUid >= 0) {
15405                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15406                                    verificationInfo.originatingUid);
15407                        }
15408                        if (verificationInfo.installerUid >= 0) {
15409                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15410                                    verificationInfo.installerUid);
15411                        }
15412                    }
15413
15414                    final PackageVerificationState verificationState = new PackageVerificationState(
15415                            requiredUid, args);
15416
15417                    mPendingVerification.append(verificationId, verificationState);
15418
15419                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15420                            receivers, verificationState);
15421
15422                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15423                    final long idleDuration = getVerificationTimeout();
15424
15425                    /*
15426                     * If any sufficient verifiers were listed in the package
15427                     * manifest, attempt to ask them.
15428                     */
15429                    if (sufficientVerifiers != null) {
15430                        final int N = sufficientVerifiers.size();
15431                        if (N == 0) {
15432                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15433                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15434                        } else {
15435                            for (int i = 0; i < N; i++) {
15436                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15437                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15438                                        verifierComponent.getPackageName(), idleDuration,
15439                                        verifierUser.getIdentifier(), false, "package verifier");
15440
15441                                final Intent sufficientIntent = new Intent(verification);
15442                                sufficientIntent.setComponent(verifierComponent);
15443                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15444                            }
15445                        }
15446                    }
15447
15448                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15449                            mRequiredVerifierPackage, receivers);
15450                    if (ret == PackageManager.INSTALL_SUCCEEDED
15451                            && mRequiredVerifierPackage != null) {
15452                        Trace.asyncTraceBegin(
15453                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15454                        /*
15455                         * Send the intent to the required verification agent,
15456                         * but only start the verification timeout after the
15457                         * target BroadcastReceivers have run.
15458                         */
15459                        verification.setComponent(requiredVerifierComponent);
15460                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15461                                mRequiredVerifierPackage, idleDuration,
15462                                verifierUser.getIdentifier(), false, "package verifier");
15463                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15464                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15465                                new BroadcastReceiver() {
15466                                    @Override
15467                                    public void onReceive(Context context, Intent intent) {
15468                                        final Message msg = mHandler
15469                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15470                                        msg.arg1 = verificationId;
15471                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15472                                    }
15473                                }, null, 0, null, null);
15474
15475                        /*
15476                         * We don't want the copy to proceed until verification
15477                         * succeeds, so null out this field.
15478                         */
15479                        mArgs = null;
15480                    }
15481                } else {
15482                    /*
15483                     * No package verification is enabled, so immediately start
15484                     * the remote call to initiate copy using temporary file.
15485                     */
15486                    ret = args.copyApk(mContainerService, true);
15487                }
15488            }
15489
15490            mRet = ret;
15491        }
15492
15493        @Override
15494        void handleReturnCode() {
15495            // If mArgs is null, then MCS couldn't be reached. When it
15496            // reconnects, it will try again to install. At that point, this
15497            // will succeed.
15498            if (mArgs != null) {
15499                processPendingInstall(mArgs, mRet);
15500            }
15501        }
15502
15503        @Override
15504        void handleServiceError() {
15505            mArgs = createInstallArgs(this);
15506            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15507        }
15508    }
15509
15510    private InstallArgs createInstallArgs(InstallParams params) {
15511        if (params.move != null) {
15512            return new MoveInstallArgs(params);
15513        } else {
15514            return new FileInstallArgs(params);
15515        }
15516    }
15517
15518    /**
15519     * Create args that describe an existing installed package. Typically used
15520     * when cleaning up old installs, or used as a move source.
15521     */
15522    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15523            String resourcePath, String[] instructionSets) {
15524        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15525    }
15526
15527    static abstract class InstallArgs {
15528        /** @see InstallParams#origin */
15529        final OriginInfo origin;
15530        /** @see InstallParams#move */
15531        final MoveInfo move;
15532
15533        final IPackageInstallObserver2 observer;
15534        // Always refers to PackageManager flags only
15535        final int installFlags;
15536        final String installerPackageName;
15537        final String volumeUuid;
15538        final UserHandle user;
15539        final String abiOverride;
15540        final String[] installGrantPermissions;
15541        /** If non-null, drop an async trace when the install completes */
15542        final String traceMethod;
15543        final int traceCookie;
15544        final PackageParser.SigningDetails signingDetails;
15545        final int installReason;
15546
15547        // The list of instruction sets supported by this app. This is currently
15548        // only used during the rmdex() phase to clean up resources. We can get rid of this
15549        // if we move dex files under the common app path.
15550        /* nullable */ String[] instructionSets;
15551
15552        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15553                int installFlags, String installerPackageName, String volumeUuid,
15554                UserHandle user, String[] instructionSets,
15555                String abiOverride, String[] installGrantPermissions,
15556                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15557                int installReason) {
15558            this.origin = origin;
15559            this.move = move;
15560            this.installFlags = installFlags;
15561            this.observer = observer;
15562            this.installerPackageName = installerPackageName;
15563            this.volumeUuid = volumeUuid;
15564            this.user = user;
15565            this.instructionSets = instructionSets;
15566            this.abiOverride = abiOverride;
15567            this.installGrantPermissions = installGrantPermissions;
15568            this.traceMethod = traceMethod;
15569            this.traceCookie = traceCookie;
15570            this.signingDetails = signingDetails;
15571            this.installReason = installReason;
15572        }
15573
15574        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15575        abstract int doPreInstall(int status);
15576
15577        /**
15578         * Rename package into final resting place. All paths on the given
15579         * scanned package should be updated to reflect the rename.
15580         */
15581        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15582        abstract int doPostInstall(int status, int uid);
15583
15584        /** @see PackageSettingBase#codePathString */
15585        abstract String getCodePath();
15586        /** @see PackageSettingBase#resourcePathString */
15587        abstract String getResourcePath();
15588
15589        // Need installer lock especially for dex file removal.
15590        abstract void cleanUpResourcesLI();
15591        abstract boolean doPostDeleteLI(boolean delete);
15592
15593        /**
15594         * Called before the source arguments are copied. This is used mostly
15595         * for MoveParams when it needs to read the source file to put it in the
15596         * destination.
15597         */
15598        int doPreCopy() {
15599            return PackageManager.INSTALL_SUCCEEDED;
15600        }
15601
15602        /**
15603         * Called after the source arguments are copied. This is used mostly for
15604         * MoveParams when it needs to read the source file to put it in the
15605         * destination.
15606         */
15607        int doPostCopy(int uid) {
15608            return PackageManager.INSTALL_SUCCEEDED;
15609        }
15610
15611        protected boolean isFwdLocked() {
15612            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15613        }
15614
15615        protected boolean isExternalAsec() {
15616            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15617        }
15618
15619        protected boolean isEphemeral() {
15620            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15621        }
15622
15623        UserHandle getUser() {
15624            return user;
15625        }
15626    }
15627
15628    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15629        if (!allCodePaths.isEmpty()) {
15630            if (instructionSets == null) {
15631                throw new IllegalStateException("instructionSet == null");
15632            }
15633            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15634            for (String codePath : allCodePaths) {
15635                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15636                    try {
15637                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15638                    } catch (InstallerException ignored) {
15639                    }
15640                }
15641            }
15642        }
15643    }
15644
15645    /**
15646     * Logic to handle installation of non-ASEC applications, including copying
15647     * and renaming logic.
15648     */
15649    class FileInstallArgs extends InstallArgs {
15650        private File codeFile;
15651        private File resourceFile;
15652
15653        // Example topology:
15654        // /data/app/com.example/base.apk
15655        // /data/app/com.example/split_foo.apk
15656        // /data/app/com.example/lib/arm/libfoo.so
15657        // /data/app/com.example/lib/arm64/libfoo.so
15658        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15659
15660        /** New install */
15661        FileInstallArgs(InstallParams params) {
15662            super(params.origin, params.move, params.observer, params.installFlags,
15663                    params.installerPackageName, params.volumeUuid,
15664                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15665                    params.grantedRuntimePermissions,
15666                    params.traceMethod, params.traceCookie, params.signingDetails,
15667                    params.installReason);
15668            if (isFwdLocked()) {
15669                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15670            }
15671        }
15672
15673        /** Existing install */
15674        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15675            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15676                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15677                    PackageManager.INSTALL_REASON_UNKNOWN);
15678            this.codeFile = (codePath != null) ? new File(codePath) : null;
15679            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15680        }
15681
15682        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15683            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15684            try {
15685                return doCopyApk(imcs, temp);
15686            } finally {
15687                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15688            }
15689        }
15690
15691        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15692            if (origin.staged) {
15693                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15694                codeFile = origin.file;
15695                resourceFile = origin.file;
15696                return PackageManager.INSTALL_SUCCEEDED;
15697            }
15698
15699            try {
15700                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15701                final File tempDir =
15702                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15703                codeFile = tempDir;
15704                resourceFile = tempDir;
15705            } catch (IOException e) {
15706                Slog.w(TAG, "Failed to create copy file: " + e);
15707                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15708            }
15709
15710            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15711                @Override
15712                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15713                    if (!FileUtils.isValidExtFilename(name)) {
15714                        throw new IllegalArgumentException("Invalid filename: " + name);
15715                    }
15716                    try {
15717                        final File file = new File(codeFile, name);
15718                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15719                                O_RDWR | O_CREAT, 0644);
15720                        Os.chmod(file.getAbsolutePath(), 0644);
15721                        return new ParcelFileDescriptor(fd);
15722                    } catch (ErrnoException e) {
15723                        throw new RemoteException("Failed to open: " + e.getMessage());
15724                    }
15725                }
15726            };
15727
15728            int ret = PackageManager.INSTALL_SUCCEEDED;
15729            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15730            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15731                Slog.e(TAG, "Failed to copy package");
15732                return ret;
15733            }
15734
15735            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15736            NativeLibraryHelper.Handle handle = null;
15737            try {
15738                handle = NativeLibraryHelper.Handle.create(codeFile);
15739                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15740                        abiOverride);
15741            } catch (IOException e) {
15742                Slog.e(TAG, "Copying native libraries failed", e);
15743                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15744            } finally {
15745                IoUtils.closeQuietly(handle);
15746            }
15747
15748            return ret;
15749        }
15750
15751        int doPreInstall(int status) {
15752            if (status != PackageManager.INSTALL_SUCCEEDED) {
15753                cleanUp();
15754            }
15755            return status;
15756        }
15757
15758        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15759            if (status != PackageManager.INSTALL_SUCCEEDED) {
15760                cleanUp();
15761                return false;
15762            }
15763
15764            final File targetDir = codeFile.getParentFile();
15765            final File beforeCodeFile = codeFile;
15766            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15767
15768            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15769            try {
15770                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15771            } catch (ErrnoException e) {
15772                Slog.w(TAG, "Failed to rename", e);
15773                return false;
15774            }
15775
15776            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15777                Slog.w(TAG, "Failed to restorecon");
15778                return false;
15779            }
15780
15781            // Reflect the rename internally
15782            codeFile = afterCodeFile;
15783            resourceFile = afterCodeFile;
15784
15785            // Reflect the rename in scanned details
15786            try {
15787                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15788            } catch (IOException e) {
15789                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15790                return false;
15791            }
15792            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15793                    afterCodeFile, pkg.baseCodePath));
15794            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15795                    afterCodeFile, pkg.splitCodePaths));
15796
15797            // Reflect the rename in app info
15798            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15799            pkg.setApplicationInfoCodePath(pkg.codePath);
15800            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15801            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15802            pkg.setApplicationInfoResourcePath(pkg.codePath);
15803            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15804            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15805
15806            return true;
15807        }
15808
15809        int doPostInstall(int status, int uid) {
15810            if (status != PackageManager.INSTALL_SUCCEEDED) {
15811                cleanUp();
15812            }
15813            return status;
15814        }
15815
15816        @Override
15817        String getCodePath() {
15818            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15819        }
15820
15821        @Override
15822        String getResourcePath() {
15823            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15824        }
15825
15826        private boolean cleanUp() {
15827            if (codeFile == null || !codeFile.exists()) {
15828                return false;
15829            }
15830
15831            removeCodePathLI(codeFile);
15832
15833            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15834                resourceFile.delete();
15835            }
15836
15837            return true;
15838        }
15839
15840        void cleanUpResourcesLI() {
15841            // Try enumerating all code paths before deleting
15842            List<String> allCodePaths = Collections.EMPTY_LIST;
15843            if (codeFile != null && codeFile.exists()) {
15844                try {
15845                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15846                    allCodePaths = pkg.getAllCodePaths();
15847                } catch (PackageParserException e) {
15848                    // Ignored; we tried our best
15849                }
15850            }
15851
15852            cleanUp();
15853            removeDexFiles(allCodePaths, instructionSets);
15854        }
15855
15856        boolean doPostDeleteLI(boolean delete) {
15857            // XXX err, shouldn't we respect the delete flag?
15858            cleanUpResourcesLI();
15859            return true;
15860        }
15861    }
15862
15863    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15864            PackageManagerException {
15865        if (copyRet < 0) {
15866            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15867                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15868                throw new PackageManagerException(copyRet, message);
15869            }
15870        }
15871    }
15872
15873    /**
15874     * Extract the StorageManagerService "container ID" from the full code path of an
15875     * .apk.
15876     */
15877    static String cidFromCodePath(String fullCodePath) {
15878        int eidx = fullCodePath.lastIndexOf("/");
15879        String subStr1 = fullCodePath.substring(0, eidx);
15880        int sidx = subStr1.lastIndexOf("/");
15881        return subStr1.substring(sidx+1, eidx);
15882    }
15883
15884    /**
15885     * Logic to handle movement of existing installed applications.
15886     */
15887    class MoveInstallArgs extends InstallArgs {
15888        private File codeFile;
15889        private File resourceFile;
15890
15891        /** New install */
15892        MoveInstallArgs(InstallParams params) {
15893            super(params.origin, params.move, params.observer, params.installFlags,
15894                    params.installerPackageName, params.volumeUuid,
15895                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15896                    params.grantedRuntimePermissions,
15897                    params.traceMethod, params.traceCookie, params.signingDetails,
15898                    params.installReason);
15899        }
15900
15901        int copyApk(IMediaContainerService imcs, boolean temp) {
15902            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15903                    + move.fromUuid + " to " + move.toUuid);
15904            synchronized (mInstaller) {
15905                try {
15906                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15907                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15908                } catch (InstallerException e) {
15909                    Slog.w(TAG, "Failed to move app", e);
15910                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15911                }
15912            }
15913
15914            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15915            resourceFile = codeFile;
15916            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15917
15918            return PackageManager.INSTALL_SUCCEEDED;
15919        }
15920
15921        int doPreInstall(int status) {
15922            if (status != PackageManager.INSTALL_SUCCEEDED) {
15923                cleanUp(move.toUuid);
15924            }
15925            return status;
15926        }
15927
15928        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15929            if (status != PackageManager.INSTALL_SUCCEEDED) {
15930                cleanUp(move.toUuid);
15931                return false;
15932            }
15933
15934            // Reflect the move in app info
15935            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15936            pkg.setApplicationInfoCodePath(pkg.codePath);
15937            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15938            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15939            pkg.setApplicationInfoResourcePath(pkg.codePath);
15940            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15941            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15942
15943            return true;
15944        }
15945
15946        int doPostInstall(int status, int uid) {
15947            if (status == PackageManager.INSTALL_SUCCEEDED) {
15948                cleanUp(move.fromUuid);
15949            } else {
15950                cleanUp(move.toUuid);
15951            }
15952            return status;
15953        }
15954
15955        @Override
15956        String getCodePath() {
15957            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15958        }
15959
15960        @Override
15961        String getResourcePath() {
15962            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15963        }
15964
15965        private boolean cleanUp(String volumeUuid) {
15966            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15967                    move.dataAppName);
15968            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15969            final int[] userIds = sUserManager.getUserIds();
15970            synchronized (mInstallLock) {
15971                // Clean up both app data and code
15972                // All package moves are frozen until finished
15973                for (int userId : userIds) {
15974                    try {
15975                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15976                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15977                    } catch (InstallerException e) {
15978                        Slog.w(TAG, String.valueOf(e));
15979                    }
15980                }
15981                removeCodePathLI(codeFile);
15982            }
15983            return true;
15984        }
15985
15986        void cleanUpResourcesLI() {
15987            throw new UnsupportedOperationException();
15988        }
15989
15990        boolean doPostDeleteLI(boolean delete) {
15991            throw new UnsupportedOperationException();
15992        }
15993    }
15994
15995    static String getAsecPackageName(String packageCid) {
15996        int idx = packageCid.lastIndexOf("-");
15997        if (idx == -1) {
15998            return packageCid;
15999        }
16000        return packageCid.substring(0, idx);
16001    }
16002
16003    // Utility method used to create code paths based on package name and available index.
16004    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16005        String idxStr = "";
16006        int idx = 1;
16007        // Fall back to default value of idx=1 if prefix is not
16008        // part of oldCodePath
16009        if (oldCodePath != null) {
16010            String subStr = oldCodePath;
16011            // Drop the suffix right away
16012            if (suffix != null && subStr.endsWith(suffix)) {
16013                subStr = subStr.substring(0, subStr.length() - suffix.length());
16014            }
16015            // If oldCodePath already contains prefix find out the
16016            // ending index to either increment or decrement.
16017            int sidx = subStr.lastIndexOf(prefix);
16018            if (sidx != -1) {
16019                subStr = subStr.substring(sidx + prefix.length());
16020                if (subStr != null) {
16021                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16022                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16023                    }
16024                    try {
16025                        idx = Integer.parseInt(subStr);
16026                        if (idx <= 1) {
16027                            idx++;
16028                        } else {
16029                            idx--;
16030                        }
16031                    } catch(NumberFormatException e) {
16032                    }
16033                }
16034            }
16035        }
16036        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16037        return prefix + idxStr;
16038    }
16039
16040    private File getNextCodePath(File targetDir, String packageName) {
16041        File result;
16042        SecureRandom random = new SecureRandom();
16043        byte[] bytes = new byte[16];
16044        do {
16045            random.nextBytes(bytes);
16046            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16047            result = new File(targetDir, packageName + "-" + suffix);
16048        } while (result.exists());
16049        return result;
16050    }
16051
16052    // Utility method that returns the relative package path with respect
16053    // to the installation directory. Like say for /data/data/com.test-1.apk
16054    // string com.test-1 is returned.
16055    static String deriveCodePathName(String codePath) {
16056        if (codePath == null) {
16057            return null;
16058        }
16059        final File codeFile = new File(codePath);
16060        final String name = codeFile.getName();
16061        if (codeFile.isDirectory()) {
16062            return name;
16063        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16064            final int lastDot = name.lastIndexOf('.');
16065            return name.substring(0, lastDot);
16066        } else {
16067            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16068            return null;
16069        }
16070    }
16071
16072    static class PackageInstalledInfo {
16073        String name;
16074        int uid;
16075        // The set of users that originally had this package installed.
16076        int[] origUsers;
16077        // The set of users that now have this package installed.
16078        int[] newUsers;
16079        PackageParser.Package pkg;
16080        int returnCode;
16081        String returnMsg;
16082        String installerPackageName;
16083        PackageRemovedInfo removedInfo;
16084        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16085
16086        public void setError(int code, String msg) {
16087            setReturnCode(code);
16088            setReturnMessage(msg);
16089            Slog.w(TAG, msg);
16090        }
16091
16092        public void setError(String msg, PackageParserException e) {
16093            setReturnCode(e.error);
16094            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16095            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16096            for (int i = 0; i < childCount; i++) {
16097                addedChildPackages.valueAt(i).setError(msg, e);
16098            }
16099            Slog.w(TAG, msg, e);
16100        }
16101
16102        public void setError(String msg, PackageManagerException e) {
16103            returnCode = e.error;
16104            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16105            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16106            for (int i = 0; i < childCount; i++) {
16107                addedChildPackages.valueAt(i).setError(msg, e);
16108            }
16109            Slog.w(TAG, msg, e);
16110        }
16111
16112        public void setReturnCode(int returnCode) {
16113            this.returnCode = returnCode;
16114            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16115            for (int i = 0; i < childCount; i++) {
16116                addedChildPackages.valueAt(i).returnCode = returnCode;
16117            }
16118        }
16119
16120        private void setReturnMessage(String returnMsg) {
16121            this.returnMsg = returnMsg;
16122            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16123            for (int i = 0; i < childCount; i++) {
16124                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16125            }
16126        }
16127
16128        // In some error cases we want to convey more info back to the observer
16129        String origPackage;
16130        String origPermission;
16131    }
16132
16133    /*
16134     * Install a non-existing package.
16135     */
16136    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16137            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16138            String volumeUuid, PackageInstalledInfo res, int installReason) {
16139        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16140
16141        // Remember this for later, in case we need to rollback this install
16142        String pkgName = pkg.packageName;
16143
16144        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16145
16146        synchronized(mPackages) {
16147            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16148            if (renamedPackage != null) {
16149                // A package with the same name is already installed, though
16150                // it has been renamed to an older name.  The package we
16151                // are trying to install should be installed as an update to
16152                // the existing one, but that has not been requested, so bail.
16153                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16154                        + " without first uninstalling package running as "
16155                        + renamedPackage);
16156                return;
16157            }
16158            if (mPackages.containsKey(pkgName)) {
16159                // Don't allow installation over an existing package with the same name.
16160                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16161                        + " without first uninstalling.");
16162                return;
16163            }
16164        }
16165
16166        try {
16167            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16168                    System.currentTimeMillis(), user);
16169
16170            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16171
16172            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16173                prepareAppDataAfterInstallLIF(newPackage);
16174
16175            } else {
16176                // Remove package from internal structures, but keep around any
16177                // data that might have already existed
16178                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16179                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16180            }
16181        } catch (PackageManagerException e) {
16182            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16183        }
16184
16185        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16186    }
16187
16188    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16189        try (DigestInputStream digestStream =
16190                new DigestInputStream(new FileInputStream(file), digest)) {
16191            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16192        }
16193    }
16194
16195    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16196            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16197            PackageInstalledInfo res, int installReason) {
16198        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16199
16200        final PackageParser.Package oldPackage;
16201        final PackageSetting ps;
16202        final String pkgName = pkg.packageName;
16203        final int[] allUsers;
16204        final int[] installedUsers;
16205
16206        synchronized(mPackages) {
16207            oldPackage = mPackages.get(pkgName);
16208            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16209
16210            // don't allow upgrade to target a release SDK from a pre-release SDK
16211            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16212                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16213            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16214                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16215            if (oldTargetsPreRelease
16216                    && !newTargetsPreRelease
16217                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16218                Slog.w(TAG, "Can't install package targeting released sdk");
16219                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16220                return;
16221            }
16222
16223            ps = mSettings.mPackages.get(pkgName);
16224
16225            // verify signatures are valid
16226            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16227            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16228                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16229                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16230                            "New package not signed by keys specified by upgrade-keysets: "
16231                                    + pkgName);
16232                    return;
16233                }
16234            } else {
16235
16236                // default to original signature matching
16237                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16238                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16239                                && !oldPackage.mSigningDetails.checkCapability(
16240                                        pkg.mSigningDetails,
16241                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16242                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16243                            "New package has a different signature: " + pkgName);
16244                    return;
16245                }
16246            }
16247
16248            // don't allow a system upgrade unless the upgrade hash matches
16249            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16250                byte[] digestBytes = null;
16251                try {
16252                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16253                    updateDigest(digest, new File(pkg.baseCodePath));
16254                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16255                        for (String path : pkg.splitCodePaths) {
16256                            updateDigest(digest, new File(path));
16257                        }
16258                    }
16259                    digestBytes = digest.digest();
16260                } catch (NoSuchAlgorithmException | IOException e) {
16261                    res.setError(INSTALL_FAILED_INVALID_APK,
16262                            "Could not compute hash: " + pkgName);
16263                    return;
16264                }
16265                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16266                    res.setError(INSTALL_FAILED_INVALID_APK,
16267                            "New package fails restrict-update check: " + pkgName);
16268                    return;
16269                }
16270                // retain upgrade restriction
16271                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16272            }
16273
16274            // Check for shared user id changes
16275            String invalidPackageName =
16276                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16277            if (invalidPackageName != null) {
16278                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16279                        "Package " + invalidPackageName + " tried to change user "
16280                                + oldPackage.mSharedUserId);
16281                return;
16282            }
16283
16284            // check if the new package supports all of the abis which the old package supports
16285            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16286            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16287            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16288                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16289                        "Update to package " + pkgName + " doesn't support multi arch");
16290                return;
16291            }
16292
16293            // In case of rollback, remember per-user/profile install state
16294            allUsers = sUserManager.getUserIds();
16295            installedUsers = ps.queryInstalledUsers(allUsers, true);
16296
16297            // don't allow an upgrade from full to ephemeral
16298            if (isInstantApp) {
16299                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16300                    for (int currentUser : allUsers) {
16301                        if (!ps.getInstantApp(currentUser)) {
16302                            // can't downgrade from full to instant
16303                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16304                                    + " for user: " + currentUser);
16305                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16306                            return;
16307                        }
16308                    }
16309                } else if (!ps.getInstantApp(user.getIdentifier())) {
16310                    // can't downgrade from full to instant
16311                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16312                            + " for user: " + user.getIdentifier());
16313                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16314                    return;
16315                }
16316            }
16317        }
16318
16319        // Update what is removed
16320        res.removedInfo = new PackageRemovedInfo(this);
16321        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16322        res.removedInfo.removedPackage = oldPackage.packageName;
16323        res.removedInfo.installerPackageName = ps.installerPackageName;
16324        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16325        res.removedInfo.isUpdate = true;
16326        res.removedInfo.origUsers = installedUsers;
16327        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16328        for (int i = 0; i < installedUsers.length; i++) {
16329            final int userId = installedUsers[i];
16330            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16331        }
16332
16333        final int childCount = (oldPackage.childPackages != null)
16334                ? oldPackage.childPackages.size() : 0;
16335        for (int i = 0; i < childCount; i++) {
16336            boolean childPackageUpdated = false;
16337            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16338            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16339            if (res.addedChildPackages != null) {
16340                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16341                if (childRes != null) {
16342                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16343                    childRes.removedInfo.removedPackage = childPkg.packageName;
16344                    if (childPs != null) {
16345                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16346                    }
16347                    childRes.removedInfo.isUpdate = true;
16348                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16349                    childPackageUpdated = true;
16350                }
16351            }
16352            if (!childPackageUpdated) {
16353                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16354                childRemovedRes.removedPackage = childPkg.packageName;
16355                if (childPs != null) {
16356                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16357                }
16358                childRemovedRes.isUpdate = false;
16359                childRemovedRes.dataRemoved = true;
16360                synchronized (mPackages) {
16361                    if (childPs != null) {
16362                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16363                    }
16364                }
16365                if (res.removedInfo.removedChildPackages == null) {
16366                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16367                }
16368                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16369            }
16370        }
16371
16372        boolean sysPkg = (isSystemApp(oldPackage));
16373        if (sysPkg) {
16374            // Set the system/privileged/oem/vendor/product flags as needed
16375            final boolean privileged =
16376                    (oldPackage.applicationInfo.privateFlags
16377                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16378            final boolean oem =
16379                    (oldPackage.applicationInfo.privateFlags
16380                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16381            final boolean vendor =
16382                    (oldPackage.applicationInfo.privateFlags
16383                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16384            final boolean product =
16385                    (oldPackage.applicationInfo.privateFlags
16386                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16387            final @ParseFlags int systemParseFlags = parseFlags;
16388            final @ScanFlags int systemScanFlags = scanFlags
16389                    | SCAN_AS_SYSTEM
16390                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16391                    | (oem ? SCAN_AS_OEM : 0)
16392                    | (vendor ? SCAN_AS_VENDOR : 0)
16393                    | (product ? SCAN_AS_PRODUCT : 0);
16394
16395            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16396                    user, allUsers, installerPackageName, res, installReason);
16397        } else {
16398            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16399                    user, allUsers, installerPackageName, res, installReason);
16400        }
16401    }
16402
16403    @Override
16404    public List<String> getPreviousCodePaths(String packageName) {
16405        final int callingUid = Binder.getCallingUid();
16406        final List<String> result = new ArrayList<>();
16407        if (getInstantAppPackageName(callingUid) != null) {
16408            return result;
16409        }
16410        final PackageSetting ps = mSettings.mPackages.get(packageName);
16411        if (ps != null
16412                && ps.oldCodePaths != null
16413                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16414            result.addAll(ps.oldCodePaths);
16415        }
16416        return result;
16417    }
16418
16419    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16420            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16421            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16422            String installerPackageName, PackageInstalledInfo res, int installReason) {
16423        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16424                + deletedPackage);
16425
16426        String pkgName = deletedPackage.packageName;
16427        boolean deletedPkg = true;
16428        boolean addedPkg = false;
16429        boolean updatedSettings = false;
16430        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16431        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16432                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16433
16434        final long origUpdateTime = (pkg.mExtras != null)
16435                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16436
16437        // First delete the existing package while retaining the data directory
16438        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16439                res.removedInfo, true, pkg)) {
16440            // If the existing package wasn't successfully deleted
16441            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16442            deletedPkg = false;
16443        } else {
16444            // Successfully deleted the old package; proceed with replace.
16445
16446            // If deleted package lived in a container, give users a chance to
16447            // relinquish resources before killing.
16448            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16449                if (DEBUG_INSTALL) {
16450                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16451                }
16452                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16453                final ArrayList<String> pkgList = new ArrayList<String>(1);
16454                pkgList.add(deletedPackage.applicationInfo.packageName);
16455                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16456            }
16457
16458            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16459                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16460
16461            try {
16462                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16463                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16464                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16465                        installReason);
16466
16467                // Update the in-memory copy of the previous code paths.
16468                PackageSetting ps = mSettings.mPackages.get(pkgName);
16469                if (!killApp) {
16470                    if (ps.oldCodePaths == null) {
16471                        ps.oldCodePaths = new ArraySet<>();
16472                    }
16473                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16474                    if (deletedPackage.splitCodePaths != null) {
16475                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16476                    }
16477                } else {
16478                    ps.oldCodePaths = null;
16479                }
16480                if (ps.childPackageNames != null) {
16481                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16482                        final String childPkgName = ps.childPackageNames.get(i);
16483                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16484                        childPs.oldCodePaths = ps.oldCodePaths;
16485                    }
16486                }
16487                prepareAppDataAfterInstallLIF(newPackage);
16488                addedPkg = true;
16489                mDexManager.notifyPackageUpdated(newPackage.packageName,
16490                        newPackage.baseCodePath, newPackage.splitCodePaths);
16491            } catch (PackageManagerException e) {
16492                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16493            }
16494        }
16495
16496        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16497            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16498
16499            // Revert all internal state mutations and added folders for the failed install
16500            if (addedPkg) {
16501                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16502                        res.removedInfo, true, null);
16503            }
16504
16505            // Restore the old package
16506            if (deletedPkg) {
16507                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16508                File restoreFile = new File(deletedPackage.codePath);
16509                // Parse old package
16510                boolean oldExternal = isExternal(deletedPackage);
16511                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16512                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16513                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16514                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16515                try {
16516                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16517                            null);
16518                } catch (PackageManagerException e) {
16519                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16520                            + e.getMessage());
16521                    return;
16522                }
16523
16524                synchronized (mPackages) {
16525                    // Ensure the installer package name up to date
16526                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16527
16528                    // Update permissions for restored package
16529                    mPermissionManager.updatePermissions(
16530                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16531                            mPermissionCallback);
16532
16533                    mSettings.writeLPr();
16534                }
16535
16536                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16537            }
16538        } else {
16539            synchronized (mPackages) {
16540                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16541                if (ps != null) {
16542                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16543                    if (res.removedInfo.removedChildPackages != null) {
16544                        final int childCount = res.removedInfo.removedChildPackages.size();
16545                        // Iterate in reverse as we may modify the collection
16546                        for (int i = childCount - 1; i >= 0; i--) {
16547                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16548                            if (res.addedChildPackages.containsKey(childPackageName)) {
16549                                res.removedInfo.removedChildPackages.removeAt(i);
16550                            } else {
16551                                PackageRemovedInfo childInfo = res.removedInfo
16552                                        .removedChildPackages.valueAt(i);
16553                                childInfo.removedForAllUsers = mPackages.get(
16554                                        childInfo.removedPackage) == null;
16555                            }
16556                        }
16557                    }
16558                }
16559            }
16560        }
16561    }
16562
16563    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16564            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16565            final @ScanFlags int scanFlags, UserHandle user,
16566            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16567            int installReason) {
16568        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16569                + ", old=" + deletedPackage);
16570
16571        final boolean disabledSystem;
16572
16573        // Remove existing system package
16574        removePackageLI(deletedPackage, true);
16575
16576        synchronized (mPackages) {
16577            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16578        }
16579        if (!disabledSystem) {
16580            // We didn't need to disable the .apk as a current system package,
16581            // which means we are replacing another update that is already
16582            // installed.  We need to make sure to delete the older one's .apk.
16583            res.removedInfo.args = createInstallArgsForExisting(0,
16584                    deletedPackage.applicationInfo.getCodePath(),
16585                    deletedPackage.applicationInfo.getResourcePath(),
16586                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16587        } else {
16588            res.removedInfo.args = null;
16589        }
16590
16591        // Successfully disabled the old package. Now proceed with re-installation
16592        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16593                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16594
16595        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16596        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16597                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16598
16599        PackageParser.Package newPackage = null;
16600        try {
16601            // Add the package to the internal data structures
16602            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16603
16604            // Set the update and install times
16605            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16606            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16607                    System.currentTimeMillis());
16608
16609            // Update the package dynamic state if succeeded
16610            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16611                // Now that the install succeeded make sure we remove data
16612                // directories for any child package the update removed.
16613                final int deletedChildCount = (deletedPackage.childPackages != null)
16614                        ? deletedPackage.childPackages.size() : 0;
16615                final int newChildCount = (newPackage.childPackages != null)
16616                        ? newPackage.childPackages.size() : 0;
16617                for (int i = 0; i < deletedChildCount; i++) {
16618                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16619                    boolean childPackageDeleted = true;
16620                    for (int j = 0; j < newChildCount; j++) {
16621                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16622                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16623                            childPackageDeleted = false;
16624                            break;
16625                        }
16626                    }
16627                    if (childPackageDeleted) {
16628                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16629                                deletedChildPkg.packageName);
16630                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16631                            PackageRemovedInfo removedChildRes = res.removedInfo
16632                                    .removedChildPackages.get(deletedChildPkg.packageName);
16633                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16634                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16635                        }
16636                    }
16637                }
16638
16639                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16640                        installReason);
16641                prepareAppDataAfterInstallLIF(newPackage);
16642
16643                mDexManager.notifyPackageUpdated(newPackage.packageName,
16644                            newPackage.baseCodePath, newPackage.splitCodePaths);
16645            }
16646        } catch (PackageManagerException e) {
16647            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16648            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16649        }
16650
16651        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16652            // Re installation failed. Restore old information
16653            // Remove new pkg information
16654            if (newPackage != null) {
16655                removeInstalledPackageLI(newPackage, true);
16656            }
16657            // Add back the old system package
16658            try {
16659                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16660            } catch (PackageManagerException e) {
16661                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16662            }
16663
16664            synchronized (mPackages) {
16665                if (disabledSystem) {
16666                    enableSystemPackageLPw(deletedPackage);
16667                }
16668
16669                // Ensure the installer package name up to date
16670                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16671
16672                // Update permissions for restored package
16673                mPermissionManager.updatePermissions(
16674                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16675                        mPermissionCallback);
16676
16677                mSettings.writeLPr();
16678            }
16679
16680            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16681                    + " after failed upgrade");
16682        }
16683    }
16684
16685    /**
16686     * Checks whether the parent or any of the child packages have a change shared
16687     * user. For a package to be a valid update the shred users of the parent and
16688     * the children should match. We may later support changing child shared users.
16689     * @param oldPkg The updated package.
16690     * @param newPkg The update package.
16691     * @return The shared user that change between the versions.
16692     */
16693    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16694            PackageParser.Package newPkg) {
16695        // Check parent shared user
16696        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16697            return newPkg.packageName;
16698        }
16699        // Check child shared users
16700        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16701        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16702        for (int i = 0; i < newChildCount; i++) {
16703            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16704            // If this child was present, did it have the same shared user?
16705            for (int j = 0; j < oldChildCount; j++) {
16706                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16707                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16708                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16709                    return newChildPkg.packageName;
16710                }
16711            }
16712        }
16713        return null;
16714    }
16715
16716    private void removeNativeBinariesLI(PackageSetting ps) {
16717        // Remove the lib path for the parent package
16718        if (ps != null) {
16719            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16720            // Remove the lib path for the child packages
16721            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16722            for (int i = 0; i < childCount; i++) {
16723                PackageSetting childPs = null;
16724                synchronized (mPackages) {
16725                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16726                }
16727                if (childPs != null) {
16728                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16729                            .legacyNativeLibraryPathString);
16730                }
16731            }
16732        }
16733    }
16734
16735    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16736        // Enable the parent package
16737        mSettings.enableSystemPackageLPw(pkg.packageName);
16738        // Enable the child packages
16739        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16740        for (int i = 0; i < childCount; i++) {
16741            PackageParser.Package childPkg = pkg.childPackages.get(i);
16742            mSettings.enableSystemPackageLPw(childPkg.packageName);
16743        }
16744    }
16745
16746    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16747            PackageParser.Package newPkg) {
16748        // Disable the parent package (parent always replaced)
16749        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16750        // Disable the child packages
16751        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16752        for (int i = 0; i < childCount; i++) {
16753            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16754            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16755            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16756        }
16757        return disabled;
16758    }
16759
16760    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16761            String installerPackageName) {
16762        // Enable the parent package
16763        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16764        // Enable the child packages
16765        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16766        for (int i = 0; i < childCount; i++) {
16767            PackageParser.Package childPkg = pkg.childPackages.get(i);
16768            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16769        }
16770    }
16771
16772    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16773            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16774        // Update the parent package setting
16775        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16776                res, user, installReason);
16777        // Update the child packages setting
16778        final int childCount = (newPackage.childPackages != null)
16779                ? newPackage.childPackages.size() : 0;
16780        for (int i = 0; i < childCount; i++) {
16781            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16782            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16783            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16784                    childRes.origUsers, childRes, user, installReason);
16785        }
16786    }
16787
16788    private void updateSettingsInternalLI(PackageParser.Package pkg,
16789            String installerPackageName, int[] allUsers, int[] installedForUsers,
16790            PackageInstalledInfo res, UserHandle user, int installReason) {
16791        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16792
16793        final String pkgName = pkg.packageName;
16794
16795        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16796        synchronized (mPackages) {
16797// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16798            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16799                    mPermissionCallback);
16800            // For system-bundled packages, we assume that installing an upgraded version
16801            // of the package implies that the user actually wants to run that new code,
16802            // so we enable the package.
16803            PackageSetting ps = mSettings.mPackages.get(pkgName);
16804            final int userId = user.getIdentifier();
16805            if (ps != null) {
16806                if (isSystemApp(pkg)) {
16807                    if (DEBUG_INSTALL) {
16808                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16809                    }
16810                    // Enable system package for requested users
16811                    if (res.origUsers != null) {
16812                        for (int origUserId : res.origUsers) {
16813                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16814                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16815                                        origUserId, installerPackageName);
16816                            }
16817                        }
16818                    }
16819                    // Also convey the prior install/uninstall state
16820                    if (allUsers != null && installedForUsers != null) {
16821                        for (int currentUserId : allUsers) {
16822                            final boolean installed = ArrayUtils.contains(
16823                                    installedForUsers, currentUserId);
16824                            if (DEBUG_INSTALL) {
16825                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16826                            }
16827                            ps.setInstalled(installed, currentUserId);
16828                        }
16829                        // these install state changes will be persisted in the
16830                        // upcoming call to mSettings.writeLPr().
16831                    }
16832                }
16833                // It's implied that when a user requests installation, they want the app to be
16834                // installed and enabled.
16835                if (userId != UserHandle.USER_ALL) {
16836                    ps.setInstalled(true, userId);
16837                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16838                }
16839
16840                // When replacing an existing package, preserve the original install reason for all
16841                // users that had the package installed before.
16842                final Set<Integer> previousUserIds = new ArraySet<>();
16843                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16844                    final int installReasonCount = res.removedInfo.installReasons.size();
16845                    for (int i = 0; i < installReasonCount; i++) {
16846                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16847                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16848                        ps.setInstallReason(previousInstallReason, previousUserId);
16849                        previousUserIds.add(previousUserId);
16850                    }
16851                }
16852
16853                // Set install reason for users that are having the package newly installed.
16854                if (userId == UserHandle.USER_ALL) {
16855                    for (int currentUserId : sUserManager.getUserIds()) {
16856                        if (!previousUserIds.contains(currentUserId)) {
16857                            ps.setInstallReason(installReason, currentUserId);
16858                        }
16859                    }
16860                } else if (!previousUserIds.contains(userId)) {
16861                    ps.setInstallReason(installReason, userId);
16862                }
16863                mSettings.writeKernelMappingLPr(ps);
16864            }
16865            res.name = pkgName;
16866            res.uid = pkg.applicationInfo.uid;
16867            res.pkg = pkg;
16868            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16869            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16870            //to update install status
16871            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16872            mSettings.writeLPr();
16873            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16874        }
16875
16876        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16877    }
16878
16879    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16880        try {
16881            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16882            installPackageLI(args, res);
16883        } finally {
16884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16885        }
16886    }
16887
16888    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16889        final int installFlags = args.installFlags;
16890        final String installerPackageName = args.installerPackageName;
16891        final String volumeUuid = args.volumeUuid;
16892        final File tmpPackageFile = new File(args.getCodePath());
16893        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16894        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16895                || (args.volumeUuid != null));
16896        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16897        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16898        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16899        final boolean virtualPreload =
16900                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16901        boolean replace = false;
16902        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16903        if (args.move != null) {
16904            // moving a complete application; perform an initial scan on the new install location
16905            scanFlags |= SCAN_INITIAL;
16906        }
16907        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16908            scanFlags |= SCAN_DONT_KILL_APP;
16909        }
16910        if (instantApp) {
16911            scanFlags |= SCAN_AS_INSTANT_APP;
16912        }
16913        if (fullApp) {
16914            scanFlags |= SCAN_AS_FULL_APP;
16915        }
16916        if (virtualPreload) {
16917            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16918        }
16919
16920        // Result object to be returned
16921        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16922        res.installerPackageName = installerPackageName;
16923
16924        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16925
16926        // Sanity check
16927        if (instantApp && (forwardLocked || onExternal)) {
16928            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16929                    + " external=" + onExternal);
16930            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16931            return;
16932        }
16933
16934        // Retrieve PackageSettings and parse package
16935        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16936                | PackageParser.PARSE_ENFORCE_CODE
16937                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16938                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16939                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16940        PackageParser pp = new PackageParser();
16941        pp.setSeparateProcesses(mSeparateProcesses);
16942        pp.setDisplayMetrics(mMetrics);
16943        pp.setCallback(mPackageParserCallback);
16944
16945        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16946        final PackageParser.Package pkg;
16947        try {
16948            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16949            DexMetadataHelper.validatePackageDexMetadata(pkg);
16950        } catch (PackageParserException e) {
16951            res.setError("Failed parse during installPackageLI", e);
16952            return;
16953        } finally {
16954            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16955        }
16956
16957        // Instant apps have several additional install-time checks.
16958        if (instantApp) {
16959            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16960                Slog.w(TAG,
16961                        "Instant app package " + pkg.packageName + " does not target at least O");
16962                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16963                        "Instant app package must target at least O");
16964                return;
16965            }
16966            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16967                Slog.w(TAG, "Instant app package " + pkg.packageName
16968                        + " does not target targetSandboxVersion 2");
16969                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16970                        "Instant app package must use targetSandboxVersion 2");
16971                return;
16972            }
16973            if (pkg.mSharedUserId != null) {
16974                Slog.w(TAG, "Instant app package " + pkg.packageName
16975                        + " may not declare sharedUserId.");
16976                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16977                        "Instant app package may not declare a sharedUserId");
16978                return;
16979            }
16980        }
16981
16982        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16983            // Static shared libraries have synthetic package names
16984            renameStaticSharedLibraryPackage(pkg);
16985
16986            // No static shared libs on external storage
16987            if (onExternal) {
16988                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16989                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16990                        "Packages declaring static-shared libs cannot be updated");
16991                return;
16992            }
16993        }
16994
16995        // If we are installing a clustered package add results for the children
16996        if (pkg.childPackages != null) {
16997            synchronized (mPackages) {
16998                final int childCount = pkg.childPackages.size();
16999                for (int i = 0; i < childCount; i++) {
17000                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17001                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17002                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17003                    childRes.pkg = childPkg;
17004                    childRes.name = childPkg.packageName;
17005                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17006                    if (childPs != null) {
17007                        childRes.origUsers = childPs.queryInstalledUsers(
17008                                sUserManager.getUserIds(), true);
17009                    }
17010                    if ((mPackages.containsKey(childPkg.packageName))) {
17011                        childRes.removedInfo = new PackageRemovedInfo(this);
17012                        childRes.removedInfo.removedPackage = childPkg.packageName;
17013                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17014                    }
17015                    if (res.addedChildPackages == null) {
17016                        res.addedChildPackages = new ArrayMap<>();
17017                    }
17018                    res.addedChildPackages.put(childPkg.packageName, childRes);
17019                }
17020            }
17021        }
17022
17023        // If package doesn't declare API override, mark that we have an install
17024        // time CPU ABI override.
17025        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17026            pkg.cpuAbiOverride = args.abiOverride;
17027        }
17028
17029        String pkgName = res.name = pkg.packageName;
17030        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17031            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17032                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17033                return;
17034            }
17035        }
17036
17037        try {
17038            // either use what we've been given or parse directly from the APK
17039            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17040                pkg.setSigningDetails(args.signingDetails);
17041            } else {
17042                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17043            }
17044        } catch (PackageParserException e) {
17045            res.setError("Failed collect during installPackageLI", e);
17046            return;
17047        }
17048
17049        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17050                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17051            Slog.w(TAG, "Instant app package " + pkg.packageName
17052                    + " is not signed with at least APK Signature Scheme v2");
17053            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17054                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17055            return;
17056        }
17057
17058        // Get rid of all references to package scan path via parser.
17059        pp = null;
17060        String oldCodePath = null;
17061        boolean systemApp = false;
17062        synchronized (mPackages) {
17063            // Check if installing already existing package
17064            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17065                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17066                if (pkg.mOriginalPackages != null
17067                        && pkg.mOriginalPackages.contains(oldName)
17068                        && mPackages.containsKey(oldName)) {
17069                    // This package is derived from an original package,
17070                    // and this device has been updating from that original
17071                    // name.  We must continue using the original name, so
17072                    // rename the new package here.
17073                    pkg.setPackageName(oldName);
17074                    pkgName = pkg.packageName;
17075                    replace = true;
17076                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17077                            + oldName + " pkgName=" + pkgName);
17078                } else if (mPackages.containsKey(pkgName)) {
17079                    // This package, under its official name, already exists
17080                    // on the device; we should replace it.
17081                    replace = true;
17082                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17083                }
17084
17085                // Child packages are installed through the parent package
17086                if (pkg.parentPackage != null) {
17087                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17088                            "Package " + pkg.packageName + " is child of package "
17089                                    + pkg.parentPackage.parentPackage + ". Child packages "
17090                                    + "can be updated only through the parent package.");
17091                    return;
17092                }
17093
17094                if (replace) {
17095                    // Prevent apps opting out from runtime permissions
17096                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17097                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17098                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17099                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17100                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17101                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17102                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17103                                        + " doesn't support runtime permissions but the old"
17104                                        + " target SDK " + oldTargetSdk + " does.");
17105                        return;
17106                    }
17107                    // Prevent persistent apps from being updated
17108                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17109                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17110                                "Package " + oldPackage.packageName + " is a persistent app. "
17111                                        + "Persistent apps are not updateable.");
17112                        return;
17113                    }
17114                    // Prevent apps from downgrading their targetSandbox.
17115                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17116                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17117                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17118                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17119                                "Package " + pkg.packageName + " new target sandbox "
17120                                + newTargetSandbox + " is incompatible with the previous value of"
17121                                + oldTargetSandbox + ".");
17122                        return;
17123                    }
17124
17125                    // Prevent installing of child packages
17126                    if (oldPackage.parentPackage != null) {
17127                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17128                                "Package " + pkg.packageName + " is child of package "
17129                                        + oldPackage.parentPackage + ". Child packages "
17130                                        + "can be updated only through the parent package.");
17131                        return;
17132                    }
17133                }
17134            }
17135
17136            PackageSetting ps = mSettings.mPackages.get(pkgName);
17137            if (ps != null) {
17138                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17139
17140                // Static shared libs have same package with different versions where
17141                // we internally use a synthetic package name to allow multiple versions
17142                // of the same package, therefore we need to compare signatures against
17143                // the package setting for the latest library version.
17144                PackageSetting signatureCheckPs = ps;
17145                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17146                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17147                    if (libraryEntry != null) {
17148                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17149                    }
17150                }
17151
17152                // Quick sanity check that we're signed correctly if updating;
17153                // we'll check this again later when scanning, but we want to
17154                // bail early here before tripping over redefined permissions.
17155                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17156                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17157                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17158                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17159                                + pkg.packageName + " upgrade keys do not match the "
17160                                + "previously installed version");
17161                        return;
17162                    }
17163                } else {
17164                    try {
17165                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17166                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17167                        // We don't care about disabledPkgSetting on install for now.
17168                        final boolean compatMatch = verifySignatures(
17169                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17170                                compareRecover);
17171                        // The new KeySets will be re-added later in the scanning process.
17172                        if (compatMatch) {
17173                            synchronized (mPackages) {
17174                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17175                            }
17176                        }
17177                    } catch (PackageManagerException e) {
17178                        res.setError(e.error, e.getMessage());
17179                        return;
17180                    }
17181                }
17182
17183                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17184                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17185                    systemApp = (ps.pkg.applicationInfo.flags &
17186                            ApplicationInfo.FLAG_SYSTEM) != 0;
17187                }
17188                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17189            }
17190
17191            int N = pkg.permissions.size();
17192            for (int i = N-1; i >= 0; i--) {
17193                final PackageParser.Permission perm = pkg.permissions.get(i);
17194                final BasePermission bp =
17195                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17196
17197                // Don't allow anyone but the system to define ephemeral permissions.
17198                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17199                        && !systemApp) {
17200                    Slog.w(TAG, "Non-System package " + pkg.packageName
17201                            + " attempting to delcare ephemeral permission "
17202                            + perm.info.name + "; Removing ephemeral.");
17203                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17204                }
17205
17206                // Check whether the newly-scanned package wants to define an already-defined perm
17207                if (bp != null) {
17208                    // If the defining package is signed with our cert, it's okay.  This
17209                    // also includes the "updating the same package" case, of course.
17210                    // "updating same package" could also involve key-rotation.
17211                    final boolean sigsOk;
17212                    final String sourcePackageName = bp.getSourcePackageName();
17213                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17214                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17215                    if (sourcePackageName.equals(pkg.packageName)
17216                            && (ksms.shouldCheckUpgradeKeySetLocked(
17217                                    sourcePackageSetting, scanFlags))) {
17218                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17219                    } else {
17220
17221                        // in the event of signing certificate rotation, we need to see if the
17222                        // package's certificate has rotated from the current one, or if it is an
17223                        // older certificate with which the current is ok with sharing permissions
17224                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17225                                        pkg.mSigningDetails,
17226                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17227                            sigsOk = true;
17228                        } else if (pkg.mSigningDetails.checkCapability(
17229                                        sourcePackageSetting.signatures.mSigningDetails,
17230                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17231
17232                            // the scanned package checks out, has signing certificate rotation
17233                            // history, and is newer; bring it over
17234                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17235                            sigsOk = true;
17236                        } else {
17237                            sigsOk = false;
17238                        }
17239                    }
17240                    if (!sigsOk) {
17241                        // If the owning package is the system itself, we log but allow
17242                        // install to proceed; we fail the install on all other permission
17243                        // redefinitions.
17244                        if (!sourcePackageName.equals("android")) {
17245                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17246                                    + pkg.packageName + " attempting to redeclare permission "
17247                                    + perm.info.name + " already owned by " + sourcePackageName);
17248                            res.origPermission = perm.info.name;
17249                            res.origPackage = sourcePackageName;
17250                            return;
17251                        } else {
17252                            Slog.w(TAG, "Package " + pkg.packageName
17253                                    + " attempting to redeclare system permission "
17254                                    + perm.info.name + "; ignoring new declaration");
17255                            pkg.permissions.remove(i);
17256                        }
17257                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17258                        // Prevent apps to change protection level to dangerous from any other
17259                        // type as this would allow a privilege escalation where an app adds a
17260                        // normal/signature permission in other app's group and later redefines
17261                        // it as dangerous leading to the group auto-grant.
17262                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17263                                == PermissionInfo.PROTECTION_DANGEROUS) {
17264                            if (bp != null && !bp.isRuntime()) {
17265                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17266                                        + "non-runtime permission " + perm.info.name
17267                                        + " to runtime; keeping old protection level");
17268                                perm.info.protectionLevel = bp.getProtectionLevel();
17269                            }
17270                        }
17271                    }
17272                }
17273            }
17274        }
17275
17276        if (systemApp) {
17277            if (onExternal) {
17278                // Abort update; system app can't be replaced with app on sdcard
17279                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17280                        "Cannot install updates to system apps on sdcard");
17281                return;
17282            } else if (instantApp) {
17283                // Abort update; system app can't be replaced with an instant app
17284                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17285                        "Cannot update a system app with an instant app");
17286                return;
17287            }
17288        }
17289
17290        if (args.move != null) {
17291            // We did an in-place move, so dex is ready to roll
17292            scanFlags |= SCAN_NO_DEX;
17293            scanFlags |= SCAN_MOVE;
17294
17295            synchronized (mPackages) {
17296                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17297                if (ps == null) {
17298                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17299                            "Missing settings for moved package " + pkgName);
17300                }
17301
17302                // We moved the entire application as-is, so bring over the
17303                // previously derived ABI information.
17304                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17305                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17306            }
17307
17308        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17309            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17310            scanFlags |= SCAN_NO_DEX;
17311
17312            try {
17313                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17314                    args.abiOverride : pkg.cpuAbiOverride);
17315                final boolean extractNativeLibs = !pkg.isLibrary();
17316                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17317            } catch (PackageManagerException pme) {
17318                Slog.e(TAG, "Error deriving application ABI", pme);
17319                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17320                return;
17321            }
17322
17323            // Shared libraries for the package need to be updated.
17324            synchronized (mPackages) {
17325                try {
17326                    updateSharedLibrariesLPr(pkg, null);
17327                } catch (PackageManagerException e) {
17328                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17329                }
17330            }
17331        }
17332
17333        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17334            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17335            return;
17336        }
17337
17338        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17339            String apkPath = null;
17340            synchronized (mPackages) {
17341                // Note that if the attacker managed to skip verify setup, for example by tampering
17342                // with the package settings, upon reboot we will do full apk verification when
17343                // verity is not detected.
17344                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17345                if (ps != null && ps.isPrivileged()) {
17346                    apkPath = pkg.baseCodePath;
17347                }
17348            }
17349
17350            if (apkPath != null) {
17351                final VerityUtils.SetupResult result =
17352                        VerityUtils.generateApkVeritySetupData(apkPath);
17353                if (result.isOk()) {
17354                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17355                    FileDescriptor fd = result.getUnownedFileDescriptor();
17356                    try {
17357                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17358                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17359                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17360                    } catch (InstallerException | IOException | DigestException |
17361                             NoSuchAlgorithmException e) {
17362                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17363                                "Failed to set up verity: " + e);
17364                        return;
17365                    } finally {
17366                        IoUtils.closeQuietly(fd);
17367                    }
17368                } else if (result.isFailed()) {
17369                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17370                    return;
17371                } else {
17372                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17373                    // reboot.
17374                }
17375            }
17376        }
17377
17378        if (!instantApp) {
17379            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17380        } else {
17381            if (DEBUG_DOMAIN_VERIFICATION) {
17382                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17383            }
17384        }
17385
17386        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17387                "installPackageLI")) {
17388            if (replace) {
17389                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17390                    // Static libs have a synthetic package name containing the version
17391                    // and cannot be updated as an update would get a new package name,
17392                    // unless this is the exact same version code which is useful for
17393                    // development.
17394                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17395                    if (existingPkg != null &&
17396                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17397                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17398                                + "static-shared libs cannot be updated");
17399                        return;
17400                    }
17401                }
17402                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17403                        installerPackageName, res, args.installReason);
17404            } else {
17405                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17406                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17407            }
17408        }
17409
17410        // Prepare the application profiles for the new code paths.
17411        // This needs to be done before invoking dexopt so that any install-time profile
17412        // can be used for optimizations.
17413        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17414
17415        // Check whether we need to dexopt the app.
17416        //
17417        // NOTE: it is IMPORTANT to call dexopt:
17418        //   - after doRename which will sync the package data from PackageParser.Package and its
17419        //     corresponding ApplicationInfo.
17420        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17421        //     uid of the application (pkg.applicationInfo.uid).
17422        //     This update happens in place!
17423        //
17424        // We only need to dexopt if the package meets ALL of the following conditions:
17425        //   1) it is not forward locked.
17426        //   2) it is not on on an external ASEC container.
17427        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17428        //
17429        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17430        // complete, so we skip this step during installation. Instead, we'll take extra time
17431        // the first time the instant app starts. It's preferred to do it this way to provide
17432        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17433        // middle of running an instant app. The default behaviour can be overridden
17434        // via gservices.
17435        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17436                && !forwardLocked
17437                && !pkg.applicationInfo.isExternalAsec()
17438                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17439                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17440
17441        if (performDexopt) {
17442            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17443            // Do not run PackageDexOptimizer through the local performDexOpt
17444            // method because `pkg` may not be in `mPackages` yet.
17445            //
17446            // Also, don't fail application installs if the dexopt step fails.
17447            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17448                    REASON_INSTALL,
17449                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17450                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17451            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17452                    null /* instructionSets */,
17453                    getOrCreateCompilerPackageStats(pkg),
17454                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17455                    dexoptOptions);
17456            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17457        }
17458
17459        // Notify BackgroundDexOptService that the package has been changed.
17460        // If this is an update of a package which used to fail to compile,
17461        // BackgroundDexOptService will remove it from its blacklist.
17462        // TODO: Layering violation
17463        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17464
17465        synchronized (mPackages) {
17466            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17467            if (ps != null) {
17468                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17469                ps.setUpdateAvailable(false /*updateAvailable*/);
17470            }
17471
17472            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17473            for (int i = 0; i < childCount; i++) {
17474                PackageParser.Package childPkg = pkg.childPackages.get(i);
17475                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17476                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17477                if (childPs != null) {
17478                    childRes.newUsers = childPs.queryInstalledUsers(
17479                            sUserManager.getUserIds(), true);
17480                }
17481            }
17482
17483            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17484                updateSequenceNumberLP(ps, res.newUsers);
17485                updateInstantAppInstallerLocked(pkgName);
17486            }
17487        }
17488    }
17489
17490    private void startIntentFilterVerifications(int userId, boolean replacing,
17491            PackageParser.Package pkg) {
17492        if (mIntentFilterVerifierComponent == null) {
17493            Slog.w(TAG, "No IntentFilter verification will not be done as "
17494                    + "there is no IntentFilterVerifier available!");
17495            return;
17496        }
17497
17498        final int verifierUid = getPackageUid(
17499                mIntentFilterVerifierComponent.getPackageName(),
17500                MATCH_DEBUG_TRIAGED_MISSING,
17501                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17502
17503        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17504        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17505        mHandler.sendMessage(msg);
17506
17507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17508        for (int i = 0; i < childCount; i++) {
17509            PackageParser.Package childPkg = pkg.childPackages.get(i);
17510            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17511            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17512            mHandler.sendMessage(msg);
17513        }
17514    }
17515
17516    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17517            PackageParser.Package pkg) {
17518        int size = pkg.activities.size();
17519        if (size == 0) {
17520            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17521                    "No activity, so no need to verify any IntentFilter!");
17522            return;
17523        }
17524
17525        final boolean hasDomainURLs = hasDomainURLs(pkg);
17526        if (!hasDomainURLs) {
17527            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17528                    "No domain URLs, so no need to verify any IntentFilter!");
17529            return;
17530        }
17531
17532        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17533                + " if any IntentFilter from the " + size
17534                + " Activities needs verification ...");
17535
17536        int count = 0;
17537        final String packageName = pkg.packageName;
17538
17539        synchronized (mPackages) {
17540            // If this is a new install and we see that we've already run verification for this
17541            // package, we have nothing to do: it means the state was restored from backup.
17542            if (!replacing) {
17543                IntentFilterVerificationInfo ivi =
17544                        mSettings.getIntentFilterVerificationLPr(packageName);
17545                if (ivi != null) {
17546                    if (DEBUG_DOMAIN_VERIFICATION) {
17547                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17548                                + ivi.getStatusString());
17549                    }
17550                    return;
17551                }
17552            }
17553
17554            // If any filters need to be verified, then all need to be.
17555            boolean needToVerify = false;
17556            for (PackageParser.Activity a : pkg.activities) {
17557                for (ActivityIntentInfo filter : a.intents) {
17558                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17559                        if (DEBUG_DOMAIN_VERIFICATION) {
17560                            Slog.d(TAG,
17561                                    "Intent filter needs verification, so processing all filters");
17562                        }
17563                        needToVerify = true;
17564                        break;
17565                    }
17566                }
17567            }
17568
17569            if (needToVerify) {
17570                final int verificationId = mIntentFilterVerificationToken++;
17571                for (PackageParser.Activity a : pkg.activities) {
17572                    for (ActivityIntentInfo filter : a.intents) {
17573                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17574                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17575                                    "Verification needed for IntentFilter:" + filter.toString());
17576                            mIntentFilterVerifier.addOneIntentFilterVerification(
17577                                    verifierUid, userId, verificationId, filter, packageName);
17578                            count++;
17579                        }
17580                    }
17581                }
17582            }
17583        }
17584
17585        if (count > 0) {
17586            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17587                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17588                    +  " for userId:" + userId);
17589            mIntentFilterVerifier.startVerifications(userId);
17590        } else {
17591            if (DEBUG_DOMAIN_VERIFICATION) {
17592                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17593            }
17594        }
17595    }
17596
17597    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17598        final ComponentName cn  = filter.activity.getComponentName();
17599        final String packageName = cn.getPackageName();
17600
17601        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17602                packageName);
17603        if (ivi == null) {
17604            return true;
17605        }
17606        int status = ivi.getStatus();
17607        switch (status) {
17608            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17609            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17610                return true;
17611
17612            default:
17613                // Nothing to do
17614                return false;
17615        }
17616    }
17617
17618    private static boolean isMultiArch(ApplicationInfo info) {
17619        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17620    }
17621
17622    private static boolean isExternal(PackageParser.Package pkg) {
17623        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17624    }
17625
17626    private static boolean isExternal(PackageSetting ps) {
17627        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17628    }
17629
17630    private static boolean isSystemApp(PackageParser.Package pkg) {
17631        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17632    }
17633
17634    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17635        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17636    }
17637
17638    private static boolean isOemApp(PackageParser.Package pkg) {
17639        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17640    }
17641
17642    private static boolean isVendorApp(PackageParser.Package pkg) {
17643        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17644    }
17645
17646    private static boolean isProductApp(PackageParser.Package pkg) {
17647        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17648    }
17649
17650    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17651        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17652    }
17653
17654    private static boolean isSystemApp(PackageSetting ps) {
17655        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17656    }
17657
17658    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17659        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17660    }
17661
17662    private int packageFlagsToInstallFlags(PackageSetting ps) {
17663        int installFlags = 0;
17664        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17665            // This existing package was an external ASEC install when we have
17666            // the external flag without a UUID
17667            installFlags |= PackageManager.INSTALL_EXTERNAL;
17668        }
17669        if (ps.isForwardLocked()) {
17670            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17671        }
17672        return installFlags;
17673    }
17674
17675    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17676        if (isExternal(pkg)) {
17677            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17678                return mSettings.getExternalVersion();
17679            } else {
17680                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17681            }
17682        } else {
17683            return mSettings.getInternalVersion();
17684        }
17685    }
17686
17687    private void deleteTempPackageFiles() {
17688        final FilenameFilter filter = new FilenameFilter() {
17689            public boolean accept(File dir, String name) {
17690                return name.startsWith("vmdl") && name.endsWith(".tmp");
17691            }
17692        };
17693        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17694            file.delete();
17695        }
17696    }
17697
17698    @Override
17699    public void deletePackageAsUser(String packageName, int versionCode,
17700            IPackageDeleteObserver observer, int userId, int flags) {
17701        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17702                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17703    }
17704
17705    @Override
17706    public void deletePackageVersioned(VersionedPackage versionedPackage,
17707            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17708        final int callingUid = Binder.getCallingUid();
17709        mContext.enforceCallingOrSelfPermission(
17710                android.Manifest.permission.DELETE_PACKAGES, null);
17711        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17712        Preconditions.checkNotNull(versionedPackage);
17713        Preconditions.checkNotNull(observer);
17714        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17715                PackageManager.VERSION_CODE_HIGHEST,
17716                Long.MAX_VALUE, "versionCode must be >= -1");
17717
17718        final String packageName = versionedPackage.getPackageName();
17719        final long versionCode = versionedPackage.getLongVersionCode();
17720        final String internalPackageName;
17721        synchronized (mPackages) {
17722            // Normalize package name to handle renamed packages and static libs
17723            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17724        }
17725
17726        final int uid = Binder.getCallingUid();
17727        if (!isOrphaned(internalPackageName)
17728                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17729            try {
17730                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17731                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17732                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17733                observer.onUserActionRequired(intent);
17734            } catch (RemoteException re) {
17735            }
17736            return;
17737        }
17738        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17739        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17740        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17741            mContext.enforceCallingOrSelfPermission(
17742                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17743                    "deletePackage for user " + userId);
17744        }
17745
17746        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17747            try {
17748                observer.onPackageDeleted(packageName,
17749                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17750            } catch (RemoteException re) {
17751            }
17752            return;
17753        }
17754
17755        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17756            try {
17757                observer.onPackageDeleted(packageName,
17758                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17759            } catch (RemoteException re) {
17760            }
17761            return;
17762        }
17763
17764        if (DEBUG_REMOVE) {
17765            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17766                    + " deleteAllUsers: " + deleteAllUsers + " version="
17767                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17768                    ? "VERSION_CODE_HIGHEST" : versionCode));
17769        }
17770        // Queue up an async operation since the package deletion may take a little while.
17771        mHandler.post(new Runnable() {
17772            public void run() {
17773                mHandler.removeCallbacks(this);
17774                int returnCode;
17775                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17776                boolean doDeletePackage = true;
17777                if (ps != null) {
17778                    final boolean targetIsInstantApp =
17779                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17780                    doDeletePackage = !targetIsInstantApp
17781                            || canViewInstantApps;
17782                }
17783                if (doDeletePackage) {
17784                    if (!deleteAllUsers) {
17785                        returnCode = deletePackageX(internalPackageName, versionCode,
17786                                userId, deleteFlags);
17787                    } else {
17788                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17789                                internalPackageName, users);
17790                        // If nobody is blocking uninstall, proceed with delete for all users
17791                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17792                            returnCode = deletePackageX(internalPackageName, versionCode,
17793                                    userId, deleteFlags);
17794                        } else {
17795                            // Otherwise uninstall individually for users with blockUninstalls=false
17796                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17797                            for (int userId : users) {
17798                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17799                                    returnCode = deletePackageX(internalPackageName, versionCode,
17800                                            userId, userFlags);
17801                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17802                                        Slog.w(TAG, "Package delete failed for user " + userId
17803                                                + ", returnCode " + returnCode);
17804                                    }
17805                                }
17806                            }
17807                            // The app has only been marked uninstalled for certain users.
17808                            // We still need to report that delete was blocked
17809                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17810                        }
17811                    }
17812                } else {
17813                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17814                }
17815                try {
17816                    observer.onPackageDeleted(packageName, returnCode, null);
17817                } catch (RemoteException e) {
17818                    Log.i(TAG, "Observer no longer exists.");
17819                } //end catch
17820            } //end run
17821        });
17822    }
17823
17824    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17825        if (pkg.staticSharedLibName != null) {
17826            return pkg.manifestPackageName;
17827        }
17828        return pkg.packageName;
17829    }
17830
17831    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17832        // Handle renamed packages
17833        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17834        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17835
17836        // Is this a static library?
17837        LongSparseArray<SharedLibraryEntry> versionedLib =
17838                mStaticLibsByDeclaringPackage.get(packageName);
17839        if (versionedLib == null || versionedLib.size() <= 0) {
17840            return packageName;
17841        }
17842
17843        // Figure out which lib versions the caller can see
17844        LongSparseLongArray versionsCallerCanSee = null;
17845        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17846        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17847                && callingAppId != Process.ROOT_UID) {
17848            versionsCallerCanSee = new LongSparseLongArray();
17849            String libName = versionedLib.valueAt(0).info.getName();
17850            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17851            if (uidPackages != null) {
17852                for (String uidPackage : uidPackages) {
17853                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17854                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17855                    if (libIdx >= 0) {
17856                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17857                        versionsCallerCanSee.append(libVersion, libVersion);
17858                    }
17859                }
17860            }
17861        }
17862
17863        // Caller can see nothing - done
17864        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17865            return packageName;
17866        }
17867
17868        // Find the version the caller can see and the app version code
17869        SharedLibraryEntry highestVersion = null;
17870        final int versionCount = versionedLib.size();
17871        for (int i = 0; i < versionCount; i++) {
17872            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17873            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17874                    libEntry.info.getLongVersion()) < 0) {
17875                continue;
17876            }
17877            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17878            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17879                if (libVersionCode == versionCode) {
17880                    return libEntry.apk;
17881                }
17882            } else if (highestVersion == null) {
17883                highestVersion = libEntry;
17884            } else if (libVersionCode  > highestVersion.info
17885                    .getDeclaringPackage().getLongVersionCode()) {
17886                highestVersion = libEntry;
17887            }
17888        }
17889
17890        if (highestVersion != null) {
17891            return highestVersion.apk;
17892        }
17893
17894        return packageName;
17895    }
17896
17897    boolean isCallerVerifier(int callingUid) {
17898        final int callingUserId = UserHandle.getUserId(callingUid);
17899        return mRequiredVerifierPackage != null &&
17900                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17901    }
17902
17903    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17904        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17905              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17906            return true;
17907        }
17908        final int callingUserId = UserHandle.getUserId(callingUid);
17909        // If the caller installed the pkgName, then allow it to silently uninstall.
17910        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17911            return true;
17912        }
17913
17914        // Allow package verifier to silently uninstall.
17915        if (mRequiredVerifierPackage != null &&
17916                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17917            return true;
17918        }
17919
17920        // Allow package uninstaller to silently uninstall.
17921        if (mRequiredUninstallerPackage != null &&
17922                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17923            return true;
17924        }
17925
17926        // Allow storage manager to silently uninstall.
17927        if (mStorageManagerPackage != null &&
17928                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17929            return true;
17930        }
17931
17932        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17933        // uninstall for device owner provisioning.
17934        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17935                == PERMISSION_GRANTED) {
17936            return true;
17937        }
17938
17939        return false;
17940    }
17941
17942    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17943        int[] result = EMPTY_INT_ARRAY;
17944        for (int userId : userIds) {
17945            if (getBlockUninstallForUser(packageName, userId)) {
17946                result = ArrayUtils.appendInt(result, userId);
17947            }
17948        }
17949        return result;
17950    }
17951
17952    @Override
17953    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17954        final int callingUid = Binder.getCallingUid();
17955        if (getInstantAppPackageName(callingUid) != null
17956                && !isCallerSameApp(packageName, callingUid)) {
17957            return false;
17958        }
17959        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17960    }
17961
17962    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17963        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17964                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17965        try {
17966            if (dpm != null) {
17967                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17968                        /* callingUserOnly =*/ false);
17969                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17970                        : deviceOwnerComponentName.getPackageName();
17971                // Does the package contains the device owner?
17972                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17973                // this check is probably not needed, since DO should be registered as a device
17974                // admin on some user too. (Original bug for this: b/17657954)
17975                if (packageName.equals(deviceOwnerPackageName)) {
17976                    return true;
17977                }
17978                // Does it contain a device admin for any user?
17979                int[] users;
17980                if (userId == UserHandle.USER_ALL) {
17981                    users = sUserManager.getUserIds();
17982                } else {
17983                    users = new int[]{userId};
17984                }
17985                for (int i = 0; i < users.length; ++i) {
17986                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17987                        return true;
17988                    }
17989                }
17990            }
17991        } catch (RemoteException e) {
17992        }
17993        return false;
17994    }
17995
17996    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17997        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17998    }
17999
18000    /**
18001     *  This method is an internal method that could be get invoked either
18002     *  to delete an installed package or to clean up a failed installation.
18003     *  After deleting an installed package, a broadcast is sent to notify any
18004     *  listeners that the package has been removed. For cleaning up a failed
18005     *  installation, the broadcast is not necessary since the package's
18006     *  installation wouldn't have sent the initial broadcast either
18007     *  The key steps in deleting a package are
18008     *  deleting the package information in internal structures like mPackages,
18009     *  deleting the packages base directories through installd
18010     *  updating mSettings to reflect current status
18011     *  persisting settings for later use
18012     *  sending a broadcast if necessary
18013     */
18014    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18015        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18016        final boolean res;
18017
18018        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18019                ? UserHandle.USER_ALL : userId;
18020
18021        if (isPackageDeviceAdmin(packageName, removeUser)) {
18022            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18023            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18024        }
18025
18026        PackageSetting uninstalledPs = null;
18027        PackageParser.Package pkg = null;
18028
18029        // for the uninstall-updates case and restricted profiles, remember the per-
18030        // user handle installed state
18031        int[] allUsers;
18032        synchronized (mPackages) {
18033            uninstalledPs = mSettings.mPackages.get(packageName);
18034            if (uninstalledPs == null) {
18035                Slog.w(TAG, "Not removing non-existent package " + packageName);
18036                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18037            }
18038
18039            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18040                    && uninstalledPs.versionCode != versionCode) {
18041                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18042                        + uninstalledPs.versionCode + " != " + versionCode);
18043                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18044            }
18045
18046            // Static shared libs can be declared by any package, so let us not
18047            // allow removing a package if it provides a lib others depend on.
18048            pkg = mPackages.get(packageName);
18049
18050            allUsers = sUserManager.getUserIds();
18051
18052            if (pkg != null && pkg.staticSharedLibName != null) {
18053                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18054                        pkg.staticSharedLibVersion);
18055                if (libEntry != null) {
18056                    for (int currUserId : allUsers) {
18057                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18058                            continue;
18059                        }
18060                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18061                                libEntry.info, 0, currUserId);
18062                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18063                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18064                                    + " hosting lib " + libEntry.info.getName() + " version "
18065                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18066                                    + " for user " + currUserId);
18067                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18068                        }
18069                    }
18070                }
18071            }
18072
18073            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18074        }
18075
18076        final int freezeUser;
18077        if (isUpdatedSystemApp(uninstalledPs)
18078                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18079            // We're downgrading a system app, which will apply to all users, so
18080            // freeze them all during the downgrade
18081            freezeUser = UserHandle.USER_ALL;
18082        } else {
18083            freezeUser = removeUser;
18084        }
18085
18086        synchronized (mInstallLock) {
18087            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18088            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18089                    deleteFlags, "deletePackageX")) {
18090                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18091                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18092            }
18093            synchronized (mPackages) {
18094                if (res) {
18095                    if (pkg != null) {
18096                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18097                    }
18098                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18099                    updateInstantAppInstallerLocked(packageName);
18100                }
18101            }
18102        }
18103
18104        if (res) {
18105            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18106            info.sendPackageRemovedBroadcasts(killApp);
18107            info.sendSystemPackageUpdatedBroadcasts();
18108            info.sendSystemPackageAppearedBroadcasts();
18109        }
18110        // Force a gc here.
18111        Runtime.getRuntime().gc();
18112        // Delete the resources here after sending the broadcast to let
18113        // other processes clean up before deleting resources.
18114        if (info.args != null) {
18115            synchronized (mInstallLock) {
18116                info.args.doPostDeleteLI(true);
18117            }
18118        }
18119
18120        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18121    }
18122
18123    static class PackageRemovedInfo {
18124        final PackageSender packageSender;
18125        String removedPackage;
18126        String installerPackageName;
18127        int uid = -1;
18128        int removedAppId = -1;
18129        int[] origUsers;
18130        int[] removedUsers = null;
18131        int[] broadcastUsers = null;
18132        int[] instantUserIds = null;
18133        SparseArray<Integer> installReasons;
18134        boolean isRemovedPackageSystemUpdate = false;
18135        boolean isUpdate;
18136        boolean dataRemoved;
18137        boolean removedForAllUsers;
18138        boolean isStaticSharedLib;
18139        // Clean up resources deleted packages.
18140        InstallArgs args = null;
18141        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18142        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18143
18144        PackageRemovedInfo(PackageSender packageSender) {
18145            this.packageSender = packageSender;
18146        }
18147
18148        void sendPackageRemovedBroadcasts(boolean killApp) {
18149            sendPackageRemovedBroadcastInternal(killApp);
18150            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18151            for (int i = 0; i < childCount; i++) {
18152                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18153                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18154            }
18155        }
18156
18157        void sendSystemPackageUpdatedBroadcasts() {
18158            if (isRemovedPackageSystemUpdate) {
18159                sendSystemPackageUpdatedBroadcastsInternal();
18160                final int childCount = (removedChildPackages != null)
18161                        ? removedChildPackages.size() : 0;
18162                for (int i = 0; i < childCount; i++) {
18163                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18164                    if (childInfo.isRemovedPackageSystemUpdate) {
18165                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18166                    }
18167                }
18168            }
18169        }
18170
18171        void sendSystemPackageAppearedBroadcasts() {
18172            final int packageCount = (appearedChildPackages != null)
18173                    ? appearedChildPackages.size() : 0;
18174            for (int i = 0; i < packageCount; i++) {
18175                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18176                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18177                    true /*sendBootCompleted*/, false /*startReceiver*/,
18178                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18179            }
18180        }
18181
18182        private void sendSystemPackageUpdatedBroadcastsInternal() {
18183            Bundle extras = new Bundle(2);
18184            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18185            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18186            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18187                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18188            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18189                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18190            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18191                null, null, 0, removedPackage, null, null, null);
18192            if (installerPackageName != null) {
18193                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18194                        removedPackage, extras, 0 /*flags*/,
18195                        installerPackageName, null, null, null);
18196                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18197                        removedPackage, extras, 0 /*flags*/,
18198                        installerPackageName, null, null, null);
18199            }
18200        }
18201
18202        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18203            // Don't send static shared library removal broadcasts as these
18204            // libs are visible only the the apps that depend on them an one
18205            // cannot remove the library if it has a dependency.
18206            if (isStaticSharedLib) {
18207                return;
18208            }
18209            Bundle extras = new Bundle(2);
18210            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18211            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18212            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18213            if (isUpdate || isRemovedPackageSystemUpdate) {
18214                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18215            }
18216            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18217            if (removedPackage != null) {
18218                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18219                    removedPackage, extras, 0, null /*targetPackage*/, null,
18220                    broadcastUsers, instantUserIds);
18221                if (installerPackageName != null) {
18222                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18223                            removedPackage, extras, 0 /*flags*/,
18224                            installerPackageName, null, broadcastUsers, instantUserIds);
18225                }
18226                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18227                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18228                        removedPackage, extras,
18229                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18230                        null, null, broadcastUsers, instantUserIds);
18231                    packageSender.notifyPackageRemoved(removedPackage);
18232                }
18233            }
18234            if (removedAppId >= 0) {
18235                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18236                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18237                    null, null, broadcastUsers, instantUserIds);
18238            }
18239        }
18240
18241        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18242            removedUsers = userIds;
18243            if (removedUsers == null) {
18244                broadcastUsers = null;
18245                return;
18246            }
18247
18248            broadcastUsers = EMPTY_INT_ARRAY;
18249            instantUserIds = EMPTY_INT_ARRAY;
18250            for (int i = userIds.length - 1; i >= 0; --i) {
18251                final int userId = userIds[i];
18252                if (deletedPackageSetting.getInstantApp(userId)) {
18253                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18254                } else {
18255                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18256                }
18257            }
18258        }
18259    }
18260
18261    /*
18262     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18263     * flag is not set, the data directory is removed as well.
18264     * make sure this flag is set for partially installed apps. If not its meaningless to
18265     * delete a partially installed application.
18266     */
18267    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18268            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18269        String packageName = ps.name;
18270        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18271        // Retrieve object to delete permissions for shared user later on
18272        final PackageParser.Package deletedPkg;
18273        final PackageSetting deletedPs;
18274        // reader
18275        synchronized (mPackages) {
18276            deletedPkg = mPackages.get(packageName);
18277            deletedPs = mSettings.mPackages.get(packageName);
18278            if (outInfo != null) {
18279                outInfo.removedPackage = packageName;
18280                outInfo.installerPackageName = ps.installerPackageName;
18281                outInfo.isStaticSharedLib = deletedPkg != null
18282                        && deletedPkg.staticSharedLibName != null;
18283                outInfo.populateUsers(deletedPs == null ? null
18284                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18285            }
18286        }
18287
18288        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18289
18290        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18291            final PackageParser.Package resolvedPkg;
18292            if (deletedPkg != null) {
18293                resolvedPkg = deletedPkg;
18294            } else {
18295                // We don't have a parsed package when it lives on an ejected
18296                // adopted storage device, so fake something together
18297                resolvedPkg = new PackageParser.Package(ps.name);
18298                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18299            }
18300            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18301                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18302            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18303            if (outInfo != null) {
18304                outInfo.dataRemoved = true;
18305            }
18306            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18307        }
18308
18309        int removedAppId = -1;
18310
18311        // writer
18312        synchronized (mPackages) {
18313            boolean installedStateChanged = false;
18314            if (deletedPs != null) {
18315                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18316                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18317                    clearDefaultBrowserIfNeeded(packageName);
18318                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18319                    removedAppId = mSettings.removePackageLPw(packageName);
18320                    if (outInfo != null) {
18321                        outInfo.removedAppId = removedAppId;
18322                    }
18323                    mPermissionManager.updatePermissions(
18324                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18325                    if (deletedPs.sharedUser != null) {
18326                        // Remove permissions associated with package. Since runtime
18327                        // permissions are per user we have to kill the removed package
18328                        // or packages running under the shared user of the removed
18329                        // package if revoking the permissions requested only by the removed
18330                        // package is successful and this causes a change in gids.
18331                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18332                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18333                                    userId);
18334                            if (userIdToKill == UserHandle.USER_ALL
18335                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18336                                // If gids changed for this user, kill all affected packages.
18337                                mHandler.post(new Runnable() {
18338                                    @Override
18339                                    public void run() {
18340                                        // This has to happen with no lock held.
18341                                        killApplication(deletedPs.name, deletedPs.appId,
18342                                                KILL_APP_REASON_GIDS_CHANGED);
18343                                    }
18344                                });
18345                                break;
18346                            }
18347                        }
18348                    }
18349                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18350                }
18351                // make sure to preserve per-user disabled state if this removal was just
18352                // a downgrade of a system app to the factory package
18353                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18354                    if (DEBUG_REMOVE) {
18355                        Slog.d(TAG, "Propagating install state across downgrade");
18356                    }
18357                    for (int userId : allUserHandles) {
18358                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18359                        if (DEBUG_REMOVE) {
18360                            Slog.d(TAG, "    user " + userId + " => " + installed);
18361                        }
18362                        if (installed != ps.getInstalled(userId)) {
18363                            installedStateChanged = true;
18364                        }
18365                        ps.setInstalled(installed, userId);
18366                    }
18367                }
18368            }
18369            // can downgrade to reader
18370            if (writeSettings) {
18371                // Save settings now
18372                mSettings.writeLPr();
18373            }
18374            if (installedStateChanged) {
18375                mSettings.writeKernelMappingLPr(ps);
18376            }
18377        }
18378        if (removedAppId != -1) {
18379            // A user ID was deleted here. Go through all users and remove it
18380            // from KeyStore.
18381            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18382        }
18383    }
18384
18385    static boolean locationIsPrivileged(String path) {
18386        try {
18387            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18388            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18389            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18390            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18391            return path.startsWith(privilegedAppDir.getCanonicalPath())
18392                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18393                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18394                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18395        } catch (IOException e) {
18396            Slog.e(TAG, "Unable to access code path " + path);
18397        }
18398        return false;
18399    }
18400
18401    static boolean locationIsOem(String path) {
18402        try {
18403            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18404        } catch (IOException e) {
18405            Slog.e(TAG, "Unable to access code path " + path);
18406        }
18407        return false;
18408    }
18409
18410    static boolean locationIsVendor(String path) {
18411        try {
18412            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18413                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18414        } catch (IOException e) {
18415            Slog.e(TAG, "Unable to access code path " + path);
18416        }
18417        return false;
18418    }
18419
18420    static boolean locationIsProduct(String path) {
18421        try {
18422            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18423        } catch (IOException e) {
18424            Slog.e(TAG, "Unable to access code path " + path);
18425        }
18426        return false;
18427    }
18428
18429    /*
18430     * Tries to delete system package.
18431     */
18432    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18433            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18434            boolean writeSettings) {
18435        if (deletedPs.parentPackageName != null) {
18436            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18437            return false;
18438        }
18439
18440        final boolean applyUserRestrictions
18441                = (allUserHandles != null) && (outInfo.origUsers != null);
18442        final PackageSetting disabledPs;
18443        // Confirm if the system package has been updated
18444        // An updated system app can be deleted. This will also have to restore
18445        // the system pkg from system partition
18446        // reader
18447        synchronized (mPackages) {
18448            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18449        }
18450
18451        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18452                + " disabledPs=" + disabledPs);
18453
18454        if (disabledPs == null) {
18455            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18456            return false;
18457        } else if (DEBUG_REMOVE) {
18458            Slog.d(TAG, "Deleting system pkg from data partition");
18459        }
18460
18461        if (DEBUG_REMOVE) {
18462            if (applyUserRestrictions) {
18463                Slog.d(TAG, "Remembering install states:");
18464                for (int userId : allUserHandles) {
18465                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18466                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18467                }
18468            }
18469        }
18470
18471        // Delete the updated package
18472        outInfo.isRemovedPackageSystemUpdate = true;
18473        if (outInfo.removedChildPackages != null) {
18474            final int childCount = (deletedPs.childPackageNames != null)
18475                    ? deletedPs.childPackageNames.size() : 0;
18476            for (int i = 0; i < childCount; i++) {
18477                String childPackageName = deletedPs.childPackageNames.get(i);
18478                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18479                        .contains(childPackageName)) {
18480                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18481                            childPackageName);
18482                    if (childInfo != null) {
18483                        childInfo.isRemovedPackageSystemUpdate = true;
18484                    }
18485                }
18486            }
18487        }
18488
18489        if (disabledPs.versionCode < deletedPs.versionCode) {
18490            // Delete data for downgrades
18491            flags &= ~PackageManager.DELETE_KEEP_DATA;
18492        } else {
18493            // Preserve data by setting flag
18494            flags |= PackageManager.DELETE_KEEP_DATA;
18495        }
18496
18497        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18498                outInfo, writeSettings, disabledPs.pkg);
18499        if (!ret) {
18500            return false;
18501        }
18502
18503        // writer
18504        synchronized (mPackages) {
18505            // NOTE: The system package always needs to be enabled; even if it's for
18506            // a compressed stub. If we don't, installing the system package fails
18507            // during scan [scanning checks the disabled packages]. We will reverse
18508            // this later, after we've "installed" the stub.
18509            // Reinstate the old system package
18510            enableSystemPackageLPw(disabledPs.pkg);
18511            // Remove any native libraries from the upgraded package.
18512            removeNativeBinariesLI(deletedPs);
18513        }
18514
18515        // Install the system package
18516        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18517        try {
18518            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18519                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18520        } catch (PackageManagerException e) {
18521            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18522                    + e.getMessage());
18523            return false;
18524        } finally {
18525            if (disabledPs.pkg.isStub) {
18526                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18527            }
18528        }
18529        return true;
18530    }
18531
18532    /**
18533     * Installs a package that's already on the system partition.
18534     */
18535    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18536            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18537            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18538                    throws PackageManagerException {
18539        @ParseFlags int parseFlags =
18540                mDefParseFlags
18541                | PackageParser.PARSE_MUST_BE_APK
18542                | PackageParser.PARSE_IS_SYSTEM_DIR;
18543        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18544        if (isPrivileged || locationIsPrivileged(codePathString)) {
18545            scanFlags |= SCAN_AS_PRIVILEGED;
18546        }
18547        if (locationIsOem(codePathString)) {
18548            scanFlags |= SCAN_AS_OEM;
18549        }
18550        if (locationIsVendor(codePathString)) {
18551            scanFlags |= SCAN_AS_VENDOR;
18552        }
18553        if (locationIsProduct(codePathString)) {
18554            scanFlags |= SCAN_AS_PRODUCT;
18555        }
18556
18557        final File codePath = new File(codePathString);
18558        final PackageParser.Package pkg =
18559                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18560
18561        try {
18562            // update shared libraries for the newly re-installed system package
18563            updateSharedLibrariesLPr(pkg, null);
18564        } catch (PackageManagerException e) {
18565            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18566        }
18567
18568        prepareAppDataAfterInstallLIF(pkg);
18569
18570        // writer
18571        synchronized (mPackages) {
18572            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18573
18574            // Propagate the permissions state as we do not want to drop on the floor
18575            // runtime permissions. The update permissions method below will take
18576            // care of removing obsolete permissions and grant install permissions.
18577            if (origPermissionState != null) {
18578                ps.getPermissionsState().copyFrom(origPermissionState);
18579            }
18580            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18581                    mPermissionCallback);
18582
18583            final boolean applyUserRestrictions
18584                    = (allUserHandles != null) && (origUserHandles != null);
18585            if (applyUserRestrictions) {
18586                boolean installedStateChanged = false;
18587                if (DEBUG_REMOVE) {
18588                    Slog.d(TAG, "Propagating install state across reinstall");
18589                }
18590                for (int userId : allUserHandles) {
18591                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18592                    if (DEBUG_REMOVE) {
18593                        Slog.d(TAG, "    user " + userId + " => " + installed);
18594                    }
18595                    if (installed != ps.getInstalled(userId)) {
18596                        installedStateChanged = true;
18597                    }
18598                    ps.setInstalled(installed, userId);
18599
18600                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18601                }
18602                // Regardless of writeSettings we need to ensure that this restriction
18603                // state propagation is persisted
18604                mSettings.writeAllUsersPackageRestrictionsLPr();
18605                if (installedStateChanged) {
18606                    mSettings.writeKernelMappingLPr(ps);
18607                }
18608            }
18609            // can downgrade to reader here
18610            if (writeSettings) {
18611                mSettings.writeLPr();
18612            }
18613        }
18614        return pkg;
18615    }
18616
18617    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18618            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18619            PackageRemovedInfo outInfo, boolean writeSettings,
18620            PackageParser.Package replacingPackage) {
18621        synchronized (mPackages) {
18622            if (outInfo != null) {
18623                outInfo.uid = ps.appId;
18624            }
18625
18626            if (outInfo != null && outInfo.removedChildPackages != null) {
18627                final int childCount = (ps.childPackageNames != null)
18628                        ? ps.childPackageNames.size() : 0;
18629                for (int i = 0; i < childCount; i++) {
18630                    String childPackageName = ps.childPackageNames.get(i);
18631                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18632                    if (childPs == null) {
18633                        return false;
18634                    }
18635                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18636                            childPackageName);
18637                    if (childInfo != null) {
18638                        childInfo.uid = childPs.appId;
18639                    }
18640                }
18641            }
18642        }
18643
18644        // Delete package data from internal structures and also remove data if flag is set
18645        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18646
18647        // Delete the child packages data
18648        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18649        for (int i = 0; i < childCount; i++) {
18650            PackageSetting childPs;
18651            synchronized (mPackages) {
18652                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18653            }
18654            if (childPs != null) {
18655                PackageRemovedInfo childOutInfo = (outInfo != null
18656                        && outInfo.removedChildPackages != null)
18657                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18658                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18659                        && (replacingPackage != null
18660                        && !replacingPackage.hasChildPackage(childPs.name))
18661                        ? flags & ~DELETE_KEEP_DATA : flags;
18662                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18663                        deleteFlags, writeSettings);
18664            }
18665        }
18666
18667        // Delete application code and resources only for parent packages
18668        if (ps.parentPackageName == null) {
18669            if (deleteCodeAndResources && (outInfo != null)) {
18670                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18671                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18672                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18673            }
18674        }
18675
18676        return true;
18677    }
18678
18679    @Override
18680    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18681            int userId) {
18682        mContext.enforceCallingOrSelfPermission(
18683                android.Manifest.permission.DELETE_PACKAGES, null);
18684        synchronized (mPackages) {
18685            // Cannot block uninstall of static shared libs as they are
18686            // considered a part of the using app (emulating static linking).
18687            // Also static libs are installed always on internal storage.
18688            PackageParser.Package pkg = mPackages.get(packageName);
18689            if (pkg != null && pkg.staticSharedLibName != null) {
18690                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18691                        + " providing static shared library: " + pkg.staticSharedLibName);
18692                return false;
18693            }
18694            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18695            mSettings.writePackageRestrictionsLPr(userId);
18696        }
18697        return true;
18698    }
18699
18700    @Override
18701    public boolean getBlockUninstallForUser(String packageName, int userId) {
18702        synchronized (mPackages) {
18703            final PackageSetting ps = mSettings.mPackages.get(packageName);
18704            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18705                return false;
18706            }
18707            return mSettings.getBlockUninstallLPr(userId, packageName);
18708        }
18709    }
18710
18711    @Override
18712    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18713        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18714        synchronized (mPackages) {
18715            PackageSetting ps = mSettings.mPackages.get(packageName);
18716            if (ps == null) {
18717                Log.w(TAG, "Package doesn't exist: " + packageName);
18718                return false;
18719            }
18720            if (systemUserApp) {
18721                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18722            } else {
18723                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18724            }
18725            mSettings.writeLPr();
18726        }
18727        return true;
18728    }
18729
18730    /*
18731     * This method handles package deletion in general
18732     */
18733    private boolean deletePackageLIF(String packageName, UserHandle user,
18734            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18735            PackageRemovedInfo outInfo, boolean writeSettings,
18736            PackageParser.Package replacingPackage) {
18737        if (packageName == null) {
18738            Slog.w(TAG, "Attempt to delete null packageName.");
18739            return false;
18740        }
18741
18742        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18743
18744        PackageSetting ps;
18745        synchronized (mPackages) {
18746            ps = mSettings.mPackages.get(packageName);
18747            if (ps == null) {
18748                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18749                return false;
18750            }
18751
18752            if (ps.parentPackageName != null && (!isSystemApp(ps)
18753                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18754                if (DEBUG_REMOVE) {
18755                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18756                            + ((user == null) ? UserHandle.USER_ALL : user));
18757                }
18758                final int removedUserId = (user != null) ? user.getIdentifier()
18759                        : UserHandle.USER_ALL;
18760
18761                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18762                    return false;
18763                }
18764                markPackageUninstalledForUserLPw(ps, user);
18765                scheduleWritePackageRestrictionsLocked(user);
18766                return true;
18767            }
18768        }
18769
18770        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18771        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18772            onSuspendingPackageRemoved(packageName, userId);
18773        }
18774
18775
18776        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18777                && user.getIdentifier() != UserHandle.USER_ALL)) {
18778            // The caller is asking that the package only be deleted for a single
18779            // user.  To do this, we just mark its uninstalled state and delete
18780            // its data. If this is a system app, we only allow this to happen if
18781            // they have set the special DELETE_SYSTEM_APP which requests different
18782            // semantics than normal for uninstalling system apps.
18783            markPackageUninstalledForUserLPw(ps, user);
18784
18785            if (!isSystemApp(ps)) {
18786                // Do not uninstall the APK if an app should be cached
18787                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18788                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18789                    // Other user still have this package installed, so all
18790                    // we need to do is clear this user's data and save that
18791                    // it is uninstalled.
18792                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18793                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18794                        return false;
18795                    }
18796                    scheduleWritePackageRestrictionsLocked(user);
18797                    return true;
18798                } else {
18799                    // We need to set it back to 'installed' so the uninstall
18800                    // broadcasts will be sent correctly.
18801                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18802                    ps.setInstalled(true, user.getIdentifier());
18803                    mSettings.writeKernelMappingLPr(ps);
18804                }
18805            } else {
18806                // This is a system app, so we assume that the
18807                // other users still have this package installed, so all
18808                // we need to do is clear this user's data and save that
18809                // it is uninstalled.
18810                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18811                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18812                    return false;
18813                }
18814                scheduleWritePackageRestrictionsLocked(user);
18815                return true;
18816            }
18817        }
18818
18819        // If we are deleting a composite package for all users, keep track
18820        // of result for each child.
18821        if (ps.childPackageNames != null && outInfo != null) {
18822            synchronized (mPackages) {
18823                final int childCount = ps.childPackageNames.size();
18824                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18825                for (int i = 0; i < childCount; i++) {
18826                    String childPackageName = ps.childPackageNames.get(i);
18827                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18828                    childInfo.removedPackage = childPackageName;
18829                    childInfo.installerPackageName = ps.installerPackageName;
18830                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18831                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18832                    if (childPs != null) {
18833                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18834                    }
18835                }
18836            }
18837        }
18838
18839        boolean ret = false;
18840        if (isSystemApp(ps)) {
18841            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18842            // When an updated system application is deleted we delete the existing resources
18843            // as well and fall back to existing code in system partition
18844            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18845        } else {
18846            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18847            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18848                    outInfo, writeSettings, replacingPackage);
18849        }
18850
18851        // Take a note whether we deleted the package for all users
18852        if (outInfo != null) {
18853            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18854            if (outInfo.removedChildPackages != null) {
18855                synchronized (mPackages) {
18856                    final int childCount = outInfo.removedChildPackages.size();
18857                    for (int i = 0; i < childCount; i++) {
18858                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18859                        if (childInfo != null) {
18860                            childInfo.removedForAllUsers = mPackages.get(
18861                                    childInfo.removedPackage) == null;
18862                        }
18863                    }
18864                }
18865            }
18866            // If we uninstalled an update to a system app there may be some
18867            // child packages that appeared as they are declared in the system
18868            // app but were not declared in the update.
18869            if (isSystemApp(ps)) {
18870                synchronized (mPackages) {
18871                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18872                    final int childCount = (updatedPs.childPackageNames != null)
18873                            ? updatedPs.childPackageNames.size() : 0;
18874                    for (int i = 0; i < childCount; i++) {
18875                        String childPackageName = updatedPs.childPackageNames.get(i);
18876                        if (outInfo.removedChildPackages == null
18877                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18878                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18879                            if (childPs == null) {
18880                                continue;
18881                            }
18882                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18883                            installRes.name = childPackageName;
18884                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18885                            installRes.pkg = mPackages.get(childPackageName);
18886                            installRes.uid = childPs.pkg.applicationInfo.uid;
18887                            if (outInfo.appearedChildPackages == null) {
18888                                outInfo.appearedChildPackages = new ArrayMap<>();
18889                            }
18890                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18891                        }
18892                    }
18893                }
18894            }
18895        }
18896
18897        return ret;
18898    }
18899
18900    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18901        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18902                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18903        for (int nextUserId : userIds) {
18904            if (DEBUG_REMOVE) {
18905                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18906            }
18907            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18908                    false /*installed*/,
18909                    true /*stopped*/,
18910                    true /*notLaunched*/,
18911                    false /*hidden*/,
18912                    false /*suspended*/,
18913                    null, /*suspendingPackage*/
18914                    null, /*dialogMessage*/
18915                    null, /*suspendedAppExtras*/
18916                    null, /*suspendedLauncherExtras*/
18917                    false /*instantApp*/,
18918                    false /*virtualPreload*/,
18919                    null /*lastDisableAppCaller*/,
18920                    null /*enabledComponents*/,
18921                    null /*disabledComponents*/,
18922                    ps.readUserState(nextUserId).domainVerificationStatus,
18923                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18924                    null /*harmfulAppWarning*/);
18925        }
18926        mSettings.writeKernelMappingLPr(ps);
18927    }
18928
18929    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18930            PackageRemovedInfo outInfo) {
18931        final PackageParser.Package pkg;
18932        synchronized (mPackages) {
18933            pkg = mPackages.get(ps.name);
18934        }
18935
18936        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18937                : new int[] {userId};
18938        for (int nextUserId : userIds) {
18939            if (DEBUG_REMOVE) {
18940                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18941                        + nextUserId);
18942            }
18943
18944            destroyAppDataLIF(pkg, userId,
18945                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18946            destroyAppProfilesLIF(pkg, userId);
18947            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18948            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18949            schedulePackageCleaning(ps.name, nextUserId, false);
18950            synchronized (mPackages) {
18951                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18952                    scheduleWritePackageRestrictionsLocked(nextUserId);
18953                }
18954                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18955            }
18956        }
18957
18958        if (outInfo != null) {
18959            outInfo.removedPackage = ps.name;
18960            outInfo.installerPackageName = ps.installerPackageName;
18961            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18962            outInfo.removedAppId = ps.appId;
18963            outInfo.removedUsers = userIds;
18964            outInfo.broadcastUsers = userIds;
18965        }
18966
18967        return true;
18968    }
18969
18970    private final class ClearStorageConnection implements ServiceConnection {
18971        IMediaContainerService mContainerService;
18972
18973        @Override
18974        public void onServiceConnected(ComponentName name, IBinder service) {
18975            synchronized (this) {
18976                mContainerService = IMediaContainerService.Stub
18977                        .asInterface(Binder.allowBlocking(service));
18978                notifyAll();
18979            }
18980        }
18981
18982        @Override
18983        public void onServiceDisconnected(ComponentName name) {
18984        }
18985    }
18986
18987    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18988        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18989
18990        final boolean mounted;
18991        if (Environment.isExternalStorageEmulated()) {
18992            mounted = true;
18993        } else {
18994            final String status = Environment.getExternalStorageState();
18995
18996            mounted = status.equals(Environment.MEDIA_MOUNTED)
18997                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18998        }
18999
19000        if (!mounted) {
19001            return;
19002        }
19003
19004        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19005        int[] users;
19006        if (userId == UserHandle.USER_ALL) {
19007            users = sUserManager.getUserIds();
19008        } else {
19009            users = new int[] { userId };
19010        }
19011        final ClearStorageConnection conn = new ClearStorageConnection();
19012        if (mContext.bindServiceAsUser(
19013                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19014            try {
19015                for (int curUser : users) {
19016                    long timeout = SystemClock.uptimeMillis() + 5000;
19017                    synchronized (conn) {
19018                        long now;
19019                        while (conn.mContainerService == null &&
19020                                (now = SystemClock.uptimeMillis()) < timeout) {
19021                            try {
19022                                conn.wait(timeout - now);
19023                            } catch (InterruptedException e) {
19024                            }
19025                        }
19026                    }
19027                    if (conn.mContainerService == null) {
19028                        return;
19029                    }
19030
19031                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19032                    clearDirectory(conn.mContainerService,
19033                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19034                    if (allData) {
19035                        clearDirectory(conn.mContainerService,
19036                                userEnv.buildExternalStorageAppDataDirs(packageName));
19037                        clearDirectory(conn.mContainerService,
19038                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19039                    }
19040                }
19041            } finally {
19042                mContext.unbindService(conn);
19043            }
19044        }
19045    }
19046
19047    @Override
19048    public void clearApplicationProfileData(String packageName) {
19049        enforceSystemOrRoot("Only the system can clear all profile data");
19050
19051        final PackageParser.Package pkg;
19052        synchronized (mPackages) {
19053            pkg = mPackages.get(packageName);
19054        }
19055
19056        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19057            synchronized (mInstallLock) {
19058                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19059            }
19060        }
19061    }
19062
19063    @Override
19064    public void clearApplicationUserData(final String packageName,
19065            final IPackageDataObserver observer, final int userId) {
19066        mContext.enforceCallingOrSelfPermission(
19067                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19068
19069        final int callingUid = Binder.getCallingUid();
19070        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19071                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19072
19073        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19074        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19075        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19076            throw new SecurityException("Cannot clear data for a protected package: "
19077                    + packageName);
19078        }
19079        // Queue up an async operation since the package deletion may take a little while.
19080        mHandler.post(new Runnable() {
19081            public void run() {
19082                mHandler.removeCallbacks(this);
19083                final boolean succeeded;
19084                if (!filterApp) {
19085                    try (PackageFreezer freezer = freezePackage(packageName,
19086                            "clearApplicationUserData")) {
19087                        synchronized (mInstallLock) {
19088                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19089                        }
19090                        clearExternalStorageDataSync(packageName, userId, true);
19091                        synchronized (mPackages) {
19092                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19093                                    packageName, userId);
19094                        }
19095                    }
19096                    if (succeeded) {
19097                        // invoke DeviceStorageMonitor's update method to clear any notifications
19098                        DeviceStorageMonitorInternal dsm = LocalServices
19099                                .getService(DeviceStorageMonitorInternal.class);
19100                        if (dsm != null) {
19101                            dsm.checkMemory();
19102                        }
19103                    }
19104                } else {
19105                    succeeded = false;
19106                }
19107                if (observer != null) {
19108                    try {
19109                        observer.onRemoveCompleted(packageName, succeeded);
19110                    } catch (RemoteException e) {
19111                        Log.i(TAG, "Observer no longer exists.");
19112                    }
19113                } //end if observer
19114            } //end run
19115        });
19116    }
19117
19118    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19119        if (packageName == null) {
19120            Slog.w(TAG, "Attempt to delete null packageName.");
19121            return false;
19122        }
19123
19124        // Try finding details about the requested package
19125        PackageParser.Package pkg;
19126        synchronized (mPackages) {
19127            pkg = mPackages.get(packageName);
19128            if (pkg == null) {
19129                final PackageSetting ps = mSettings.mPackages.get(packageName);
19130                if (ps != null) {
19131                    pkg = ps.pkg;
19132                }
19133            }
19134
19135            if (pkg == null) {
19136                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19137                return false;
19138            }
19139
19140            PackageSetting ps = (PackageSetting) pkg.mExtras;
19141            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19142        }
19143
19144        clearAppDataLIF(pkg, userId,
19145                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19146
19147        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19148        removeKeystoreDataIfNeeded(userId, appId);
19149
19150        UserManagerInternal umInternal = getUserManagerInternal();
19151        final int flags;
19152        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19153            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19154        } else if (umInternal.isUserRunning(userId)) {
19155            flags = StorageManager.FLAG_STORAGE_DE;
19156        } else {
19157            flags = 0;
19158        }
19159        prepareAppDataContentsLIF(pkg, userId, flags);
19160
19161        return true;
19162    }
19163
19164    /**
19165     * Reverts user permission state changes (permissions and flags) in
19166     * all packages for a given user.
19167     *
19168     * @param userId The device user for which to do a reset.
19169     */
19170    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19171        final int packageCount = mPackages.size();
19172        for (int i = 0; i < packageCount; i++) {
19173            PackageParser.Package pkg = mPackages.valueAt(i);
19174            PackageSetting ps = (PackageSetting) pkg.mExtras;
19175            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19176        }
19177    }
19178
19179    private void resetNetworkPolicies(int userId) {
19180        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19181    }
19182
19183    /**
19184     * Reverts user permission state changes (permissions and flags).
19185     *
19186     * @param ps The package for which to reset.
19187     * @param userId The device user for which to do a reset.
19188     */
19189    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19190            final PackageSetting ps, final int userId) {
19191        if (ps.pkg == null) {
19192            return;
19193        }
19194
19195        // These are flags that can change base on user actions.
19196        final int userSettableMask = FLAG_PERMISSION_USER_SET
19197                | FLAG_PERMISSION_USER_FIXED
19198                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19199                | FLAG_PERMISSION_REVIEW_REQUIRED;
19200
19201        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19202                | FLAG_PERMISSION_POLICY_FIXED;
19203
19204        boolean writeInstallPermissions = false;
19205        boolean writeRuntimePermissions = false;
19206
19207        final int permissionCount = ps.pkg.requestedPermissions.size();
19208        for (int i = 0; i < permissionCount; i++) {
19209            final String permName = ps.pkg.requestedPermissions.get(i);
19210            final BasePermission bp =
19211                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19212            if (bp == null) {
19213                continue;
19214            }
19215
19216            // If shared user we just reset the state to which only this app contributed.
19217            if (ps.sharedUser != null) {
19218                boolean used = false;
19219                final int packageCount = ps.sharedUser.packages.size();
19220                for (int j = 0; j < packageCount; j++) {
19221                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19222                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19223                            && pkg.pkg.requestedPermissions.contains(permName)) {
19224                        used = true;
19225                        break;
19226                    }
19227                }
19228                if (used) {
19229                    continue;
19230                }
19231            }
19232
19233            final PermissionsState permissionsState = ps.getPermissionsState();
19234
19235            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19236
19237            // Always clear the user settable flags.
19238            final boolean hasInstallState =
19239                    permissionsState.getInstallPermissionState(permName) != null;
19240            // If permission review is enabled and this is a legacy app, mark the
19241            // permission as requiring a review as this is the initial state.
19242            int flags = 0;
19243            if (mSettings.mPermissions.mPermissionReviewRequired
19244                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19245                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19246            }
19247            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19248                if (hasInstallState) {
19249                    writeInstallPermissions = true;
19250                } else {
19251                    writeRuntimePermissions = true;
19252                }
19253            }
19254
19255            // Below is only runtime permission handling.
19256            if (!bp.isRuntime()) {
19257                continue;
19258            }
19259
19260            // Never clobber system or policy.
19261            if ((oldFlags & policyOrSystemFlags) != 0) {
19262                continue;
19263            }
19264
19265            // If this permission was granted by default, make sure it is.
19266            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19267                if (permissionsState.grantRuntimePermission(bp, userId)
19268                        != PERMISSION_OPERATION_FAILURE) {
19269                    writeRuntimePermissions = true;
19270                }
19271            // If permission review is enabled the permissions for a legacy apps
19272            // are represented as constantly granted runtime ones, so don't revoke.
19273            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19274                // Otherwise, reset the permission.
19275                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19276                switch (revokeResult) {
19277                    case PERMISSION_OPERATION_SUCCESS:
19278                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19279                        writeRuntimePermissions = true;
19280                        final int appId = ps.appId;
19281                        mHandler.post(new Runnable() {
19282                            @Override
19283                            public void run() {
19284                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19285                            }
19286                        });
19287                    } break;
19288                }
19289            }
19290        }
19291
19292        // Synchronously write as we are taking permissions away.
19293        if (writeRuntimePermissions) {
19294            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19295        }
19296
19297        // Synchronously write as we are taking permissions away.
19298        if (writeInstallPermissions) {
19299            mSettings.writeLPr();
19300        }
19301    }
19302
19303    /**
19304     * Remove entries from the keystore daemon. Will only remove it if the
19305     * {@code appId} is valid.
19306     */
19307    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19308        if (appId < 0) {
19309            return;
19310        }
19311
19312        final KeyStore keyStore = KeyStore.getInstance();
19313        if (keyStore != null) {
19314            if (userId == UserHandle.USER_ALL) {
19315                for (final int individual : sUserManager.getUserIds()) {
19316                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19317                }
19318            } else {
19319                keyStore.clearUid(UserHandle.getUid(userId, appId));
19320            }
19321        } else {
19322            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19323        }
19324    }
19325
19326    @Override
19327    public void deleteApplicationCacheFiles(final String packageName,
19328            final IPackageDataObserver observer) {
19329        final int userId = UserHandle.getCallingUserId();
19330        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19331    }
19332
19333    @Override
19334    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19335            final IPackageDataObserver observer) {
19336        final int callingUid = Binder.getCallingUid();
19337        if (mContext.checkCallingOrSelfPermission(
19338                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19339                != PackageManager.PERMISSION_GRANTED) {
19340            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19341            if (mContext.checkCallingOrSelfPermission(
19342                    android.Manifest.permission.DELETE_CACHE_FILES)
19343                    == PackageManager.PERMISSION_GRANTED) {
19344                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19345                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19346                        ", silently ignoring");
19347                return;
19348            }
19349            mContext.enforceCallingOrSelfPermission(
19350                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19351        }
19352        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19353                /* requireFullPermission= */ true, /* checkShell= */ false,
19354                "delete application cache files");
19355        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19356                android.Manifest.permission.ACCESS_INSTANT_APPS);
19357
19358        final PackageParser.Package pkg;
19359        synchronized (mPackages) {
19360            pkg = mPackages.get(packageName);
19361        }
19362
19363        // Queue up an async operation since the package deletion may take a little while.
19364        mHandler.post(new Runnable() {
19365            public void run() {
19366                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19367                boolean doClearData = true;
19368                if (ps != null) {
19369                    final boolean targetIsInstantApp =
19370                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19371                    doClearData = !targetIsInstantApp
19372                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19373                }
19374                if (doClearData) {
19375                    synchronized (mInstallLock) {
19376                        final int flags = StorageManager.FLAG_STORAGE_DE
19377                                | StorageManager.FLAG_STORAGE_CE;
19378                        // We're only clearing cache files, so we don't care if the
19379                        // app is unfrozen and still able to run
19380                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19381                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19382                    }
19383                    clearExternalStorageDataSync(packageName, userId, false);
19384                }
19385                if (observer != null) {
19386                    try {
19387                        observer.onRemoveCompleted(packageName, true);
19388                    } catch (RemoteException e) {
19389                        Log.i(TAG, "Observer no longer exists.");
19390                    }
19391                }
19392            }
19393        });
19394    }
19395
19396    @Override
19397    public void getPackageSizeInfo(final String packageName, int userHandle,
19398            final IPackageStatsObserver observer) {
19399        throw new UnsupportedOperationException(
19400                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19401    }
19402
19403    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19404        final PackageSetting ps;
19405        synchronized (mPackages) {
19406            ps = mSettings.mPackages.get(packageName);
19407            if (ps == null) {
19408                Slog.w(TAG, "Failed to find settings for " + packageName);
19409                return false;
19410            }
19411        }
19412
19413        final String[] packageNames = { packageName };
19414        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19415        final String[] codePaths = { ps.codePathString };
19416
19417        try {
19418            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19419                    ps.appId, ceDataInodes, codePaths, stats);
19420
19421            // For now, ignore code size of packages on system partition
19422            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19423                stats.codeSize = 0;
19424            }
19425
19426            // External clients expect these to be tracked separately
19427            stats.dataSize -= stats.cacheSize;
19428
19429        } catch (InstallerException e) {
19430            Slog.w(TAG, String.valueOf(e));
19431            return false;
19432        }
19433
19434        return true;
19435    }
19436
19437    private int getUidTargetSdkVersionLockedLPr(int uid) {
19438        Object obj = mSettings.getUserIdLPr(uid);
19439        if (obj instanceof SharedUserSetting) {
19440            final SharedUserSetting sus = (SharedUserSetting) obj;
19441            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19442            final Iterator<PackageSetting> it = sus.packages.iterator();
19443            while (it.hasNext()) {
19444                final PackageSetting ps = it.next();
19445                if (ps.pkg != null) {
19446                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19447                    if (v < vers) vers = v;
19448                }
19449            }
19450            return vers;
19451        } else if (obj instanceof PackageSetting) {
19452            final PackageSetting ps = (PackageSetting) obj;
19453            if (ps.pkg != null) {
19454                return ps.pkg.applicationInfo.targetSdkVersion;
19455            }
19456        }
19457        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19458    }
19459
19460    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19461        final PackageParser.Package p = mPackages.get(packageName);
19462        if (p != null) {
19463            return p.applicationInfo.targetSdkVersion;
19464        }
19465        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19466    }
19467
19468    @Override
19469    public void addPreferredActivity(IntentFilter filter, int match,
19470            ComponentName[] set, ComponentName activity, int userId) {
19471        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19472                "Adding preferred");
19473    }
19474
19475    private void addPreferredActivityInternal(IntentFilter filter, int match,
19476            ComponentName[] set, ComponentName activity, boolean always, int userId,
19477            String opname) {
19478        // writer
19479        int callingUid = Binder.getCallingUid();
19480        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19481                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19482        if (filter.countActions() == 0) {
19483            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19484            return;
19485        }
19486        synchronized (mPackages) {
19487            if (mContext.checkCallingOrSelfPermission(
19488                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19489                    != PackageManager.PERMISSION_GRANTED) {
19490                if (getUidTargetSdkVersionLockedLPr(callingUid)
19491                        < Build.VERSION_CODES.FROYO) {
19492                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19493                            + callingUid);
19494                    return;
19495                }
19496                mContext.enforceCallingOrSelfPermission(
19497                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19498            }
19499
19500            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19501            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19502                    + userId + ":");
19503            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19504            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19505            scheduleWritePackageRestrictionsLocked(userId);
19506            postPreferredActivityChangedBroadcast(userId);
19507        }
19508    }
19509
19510    private void postPreferredActivityChangedBroadcast(int userId) {
19511        mHandler.post(() -> {
19512            final IActivityManager am = ActivityManager.getService();
19513            if (am == null) {
19514                return;
19515            }
19516
19517            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19518            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19519            try {
19520                am.broadcastIntent(null, intent, null, null,
19521                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19522                        null, false, false, userId);
19523            } catch (RemoteException e) {
19524            }
19525        });
19526    }
19527
19528    @Override
19529    public void replacePreferredActivity(IntentFilter filter, int match,
19530            ComponentName[] set, ComponentName activity, int userId) {
19531        if (filter.countActions() != 1) {
19532            throw new IllegalArgumentException(
19533                    "replacePreferredActivity expects filter to have only 1 action.");
19534        }
19535        if (filter.countDataAuthorities() != 0
19536                || filter.countDataPaths() != 0
19537                || filter.countDataSchemes() > 1
19538                || filter.countDataTypes() != 0) {
19539            throw new IllegalArgumentException(
19540                    "replacePreferredActivity expects filter to have no data authorities, " +
19541                    "paths, or types; and at most one scheme.");
19542        }
19543
19544        final int callingUid = Binder.getCallingUid();
19545        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19546                true /* requireFullPermission */, false /* checkShell */,
19547                "replace preferred activity");
19548        synchronized (mPackages) {
19549            if (mContext.checkCallingOrSelfPermission(
19550                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19551                    != PackageManager.PERMISSION_GRANTED) {
19552                if (getUidTargetSdkVersionLockedLPr(callingUid)
19553                        < Build.VERSION_CODES.FROYO) {
19554                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19555                            + Binder.getCallingUid());
19556                    return;
19557                }
19558                mContext.enforceCallingOrSelfPermission(
19559                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19560            }
19561
19562            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19563            if (pir != null) {
19564                // Get all of the existing entries that exactly match this filter.
19565                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19566                if (existing != null && existing.size() == 1) {
19567                    PreferredActivity cur = existing.get(0);
19568                    if (DEBUG_PREFERRED) {
19569                        Slog.i(TAG, "Checking replace of preferred:");
19570                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19571                        if (!cur.mPref.mAlways) {
19572                            Slog.i(TAG, "  -- CUR; not mAlways!");
19573                        } else {
19574                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19575                            Slog.i(TAG, "  -- CUR: mSet="
19576                                    + Arrays.toString(cur.mPref.mSetComponents));
19577                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19578                            Slog.i(TAG, "  -- NEW: mMatch="
19579                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19580                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19581                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19582                        }
19583                    }
19584                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19585                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19586                            && cur.mPref.sameSet(set)) {
19587                        // Setting the preferred activity to what it happens to be already
19588                        if (DEBUG_PREFERRED) {
19589                            Slog.i(TAG, "Replacing with same preferred activity "
19590                                    + cur.mPref.mShortComponent + " for user "
19591                                    + userId + ":");
19592                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19593                        }
19594                        return;
19595                    }
19596                }
19597
19598                if (existing != null) {
19599                    if (DEBUG_PREFERRED) {
19600                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19601                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19602                    }
19603                    for (int i = 0; i < existing.size(); i++) {
19604                        PreferredActivity pa = existing.get(i);
19605                        if (DEBUG_PREFERRED) {
19606                            Slog.i(TAG, "Removing existing preferred activity "
19607                                    + pa.mPref.mComponent + ":");
19608                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19609                        }
19610                        pir.removeFilter(pa);
19611                    }
19612                }
19613            }
19614            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19615                    "Replacing preferred");
19616        }
19617    }
19618
19619    @Override
19620    public void clearPackagePreferredActivities(String packageName) {
19621        final int callingUid = Binder.getCallingUid();
19622        if (getInstantAppPackageName(callingUid) != null) {
19623            return;
19624        }
19625        // writer
19626        synchronized (mPackages) {
19627            PackageParser.Package pkg = mPackages.get(packageName);
19628            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19629                if (mContext.checkCallingOrSelfPermission(
19630                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19631                        != PackageManager.PERMISSION_GRANTED) {
19632                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19633                            < Build.VERSION_CODES.FROYO) {
19634                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19635                                + callingUid);
19636                        return;
19637                    }
19638                    mContext.enforceCallingOrSelfPermission(
19639                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19640                }
19641            }
19642            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19643            if (ps != null
19644                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19645                return;
19646            }
19647            int user = UserHandle.getCallingUserId();
19648            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19649                scheduleWritePackageRestrictionsLocked(user);
19650            }
19651        }
19652    }
19653
19654    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19655    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19656        ArrayList<PreferredActivity> removed = null;
19657        boolean changed = false;
19658        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19659            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19660            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19661            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19662                continue;
19663            }
19664            Iterator<PreferredActivity> it = pir.filterIterator();
19665            while (it.hasNext()) {
19666                PreferredActivity pa = it.next();
19667                // Mark entry for removal only if it matches the package name
19668                // and the entry is of type "always".
19669                if (packageName == null ||
19670                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19671                                && pa.mPref.mAlways)) {
19672                    if (removed == null) {
19673                        removed = new ArrayList<PreferredActivity>();
19674                    }
19675                    removed.add(pa);
19676                }
19677            }
19678            if (removed != null) {
19679                for (int j=0; j<removed.size(); j++) {
19680                    PreferredActivity pa = removed.get(j);
19681                    pir.removeFilter(pa);
19682                }
19683                changed = true;
19684            }
19685        }
19686        if (changed) {
19687            postPreferredActivityChangedBroadcast(userId);
19688        }
19689        return changed;
19690    }
19691
19692    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19693    private void clearIntentFilterVerificationsLPw(int userId) {
19694        final int packageCount = mPackages.size();
19695        for (int i = 0; i < packageCount; i++) {
19696            PackageParser.Package pkg = mPackages.valueAt(i);
19697            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19698        }
19699    }
19700
19701    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19702    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19703        if (userId == UserHandle.USER_ALL) {
19704            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19705                    sUserManager.getUserIds())) {
19706                for (int oneUserId : sUserManager.getUserIds()) {
19707                    scheduleWritePackageRestrictionsLocked(oneUserId);
19708                }
19709            }
19710        } else {
19711            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19712                scheduleWritePackageRestrictionsLocked(userId);
19713            }
19714        }
19715    }
19716
19717    /** Clears state for all users, and touches intent filter verification policy */
19718    void clearDefaultBrowserIfNeeded(String packageName) {
19719        for (int oneUserId : sUserManager.getUserIds()) {
19720            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19721        }
19722    }
19723
19724    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19725        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19726        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19727            if (packageName.equals(defaultBrowserPackageName)) {
19728                setDefaultBrowserPackageName(null, userId);
19729            }
19730        }
19731    }
19732
19733    @Override
19734    public void resetApplicationPreferences(int userId) {
19735        mContext.enforceCallingOrSelfPermission(
19736                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19737        final long identity = Binder.clearCallingIdentity();
19738        // writer
19739        try {
19740            synchronized (mPackages) {
19741                clearPackagePreferredActivitiesLPw(null, userId);
19742                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19743                // TODO: We have to reset the default SMS and Phone. This requires
19744                // significant refactoring to keep all default apps in the package
19745                // manager (cleaner but more work) or have the services provide
19746                // callbacks to the package manager to request a default app reset.
19747                applyFactoryDefaultBrowserLPw(userId);
19748                clearIntentFilterVerificationsLPw(userId);
19749                primeDomainVerificationsLPw(userId);
19750                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19751                scheduleWritePackageRestrictionsLocked(userId);
19752            }
19753            resetNetworkPolicies(userId);
19754        } finally {
19755            Binder.restoreCallingIdentity(identity);
19756        }
19757    }
19758
19759    @Override
19760    public int getPreferredActivities(List<IntentFilter> outFilters,
19761            List<ComponentName> outActivities, String packageName) {
19762        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19763            return 0;
19764        }
19765        int num = 0;
19766        final int userId = UserHandle.getCallingUserId();
19767        // reader
19768        synchronized (mPackages) {
19769            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19770            if (pir != null) {
19771                final Iterator<PreferredActivity> it = pir.filterIterator();
19772                while (it.hasNext()) {
19773                    final PreferredActivity pa = it.next();
19774                    if (packageName == null
19775                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19776                                    && pa.mPref.mAlways)) {
19777                        if (outFilters != null) {
19778                            outFilters.add(new IntentFilter(pa));
19779                        }
19780                        if (outActivities != null) {
19781                            outActivities.add(pa.mPref.mComponent);
19782                        }
19783                    }
19784                }
19785            }
19786        }
19787
19788        return num;
19789    }
19790
19791    @Override
19792    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19793            int userId) {
19794        int callingUid = Binder.getCallingUid();
19795        if (callingUid != Process.SYSTEM_UID) {
19796            throw new SecurityException(
19797                    "addPersistentPreferredActivity can only be run by the system");
19798        }
19799        if (filter.countActions() == 0) {
19800            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19801            return;
19802        }
19803        synchronized (mPackages) {
19804            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19805                    ":");
19806            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19807            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19808                    new PersistentPreferredActivity(filter, activity));
19809            scheduleWritePackageRestrictionsLocked(userId);
19810            postPreferredActivityChangedBroadcast(userId);
19811        }
19812    }
19813
19814    @Override
19815    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19816        int callingUid = Binder.getCallingUid();
19817        if (callingUid != Process.SYSTEM_UID) {
19818            throw new SecurityException(
19819                    "clearPackagePersistentPreferredActivities can only be run by the system");
19820        }
19821        ArrayList<PersistentPreferredActivity> removed = null;
19822        boolean changed = false;
19823        synchronized (mPackages) {
19824            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19825                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19826                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19827                        .valueAt(i);
19828                if (userId != thisUserId) {
19829                    continue;
19830                }
19831                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19832                while (it.hasNext()) {
19833                    PersistentPreferredActivity ppa = it.next();
19834                    // Mark entry for removal only if it matches the package name.
19835                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19836                        if (removed == null) {
19837                            removed = new ArrayList<PersistentPreferredActivity>();
19838                        }
19839                        removed.add(ppa);
19840                    }
19841                }
19842                if (removed != null) {
19843                    for (int j=0; j<removed.size(); j++) {
19844                        PersistentPreferredActivity ppa = removed.get(j);
19845                        ppir.removeFilter(ppa);
19846                    }
19847                    changed = true;
19848                }
19849            }
19850
19851            if (changed) {
19852                scheduleWritePackageRestrictionsLocked(userId);
19853                postPreferredActivityChangedBroadcast(userId);
19854            }
19855        }
19856    }
19857
19858    /**
19859     * Common machinery for picking apart a restored XML blob and passing
19860     * it to a caller-supplied functor to be applied to the running system.
19861     */
19862    private void restoreFromXml(XmlPullParser parser, int userId,
19863            String expectedStartTag, BlobXmlRestorer functor)
19864            throws IOException, XmlPullParserException {
19865        int type;
19866        while ((type = parser.next()) != XmlPullParser.START_TAG
19867                && type != XmlPullParser.END_DOCUMENT) {
19868        }
19869        if (type != XmlPullParser.START_TAG) {
19870            // oops didn't find a start tag?!
19871            if (DEBUG_BACKUP) {
19872                Slog.e(TAG, "Didn't find start tag during restore");
19873            }
19874            return;
19875        }
19876Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19877        // this is supposed to be TAG_PREFERRED_BACKUP
19878        if (!expectedStartTag.equals(parser.getName())) {
19879            if (DEBUG_BACKUP) {
19880                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19881            }
19882            return;
19883        }
19884
19885        // skip interfering stuff, then we're aligned with the backing implementation
19886        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19887Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19888        functor.apply(parser, userId);
19889    }
19890
19891    private interface BlobXmlRestorer {
19892        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19893    }
19894
19895    /**
19896     * Non-Binder method, support for the backup/restore mechanism: write the
19897     * full set of preferred activities in its canonical XML format.  Returns the
19898     * XML output as a byte array, or null if there is none.
19899     */
19900    @Override
19901    public byte[] getPreferredActivityBackup(int userId) {
19902        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19903            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19904        }
19905
19906        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19907        try {
19908            final XmlSerializer serializer = new FastXmlSerializer();
19909            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19910            serializer.startDocument(null, true);
19911            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19912
19913            synchronized (mPackages) {
19914                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19915            }
19916
19917            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19918            serializer.endDocument();
19919            serializer.flush();
19920        } catch (Exception e) {
19921            if (DEBUG_BACKUP) {
19922                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19923            }
19924            return null;
19925        }
19926
19927        return dataStream.toByteArray();
19928    }
19929
19930    @Override
19931    public void restorePreferredActivities(byte[] backup, int userId) {
19932        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19933            throw new SecurityException("Only the system may call restorePreferredActivities()");
19934        }
19935
19936        try {
19937            final XmlPullParser parser = Xml.newPullParser();
19938            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19939            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19940                    new BlobXmlRestorer() {
19941                        @Override
19942                        public void apply(XmlPullParser parser, int userId)
19943                                throws XmlPullParserException, IOException {
19944                            synchronized (mPackages) {
19945                                mSettings.readPreferredActivitiesLPw(parser, userId);
19946                            }
19947                        }
19948                    } );
19949        } catch (Exception e) {
19950            if (DEBUG_BACKUP) {
19951                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19952            }
19953        }
19954    }
19955
19956    /**
19957     * Non-Binder method, support for the backup/restore mechanism: write the
19958     * default browser (etc) settings in its canonical XML format.  Returns the default
19959     * browser XML representation as a byte array, or null if there is none.
19960     */
19961    @Override
19962    public byte[] getDefaultAppsBackup(int userId) {
19963        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19964            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19965        }
19966
19967        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19968        try {
19969            final XmlSerializer serializer = new FastXmlSerializer();
19970            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19971            serializer.startDocument(null, true);
19972            serializer.startTag(null, TAG_DEFAULT_APPS);
19973
19974            synchronized (mPackages) {
19975                mSettings.writeDefaultAppsLPr(serializer, userId);
19976            }
19977
19978            serializer.endTag(null, TAG_DEFAULT_APPS);
19979            serializer.endDocument();
19980            serializer.flush();
19981        } catch (Exception e) {
19982            if (DEBUG_BACKUP) {
19983                Slog.e(TAG, "Unable to write default apps for backup", e);
19984            }
19985            return null;
19986        }
19987
19988        return dataStream.toByteArray();
19989    }
19990
19991    @Override
19992    public void restoreDefaultApps(byte[] backup, int userId) {
19993        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19994            throw new SecurityException("Only the system may call restoreDefaultApps()");
19995        }
19996
19997        try {
19998            final XmlPullParser parser = Xml.newPullParser();
19999            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20000            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20001                    new BlobXmlRestorer() {
20002                        @Override
20003                        public void apply(XmlPullParser parser, int userId)
20004                                throws XmlPullParserException, IOException {
20005                            synchronized (mPackages) {
20006                                mSettings.readDefaultAppsLPw(parser, userId);
20007                            }
20008                        }
20009                    } );
20010        } catch (Exception e) {
20011            if (DEBUG_BACKUP) {
20012                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20013            }
20014        }
20015    }
20016
20017    @Override
20018    public byte[] getIntentFilterVerificationBackup(int userId) {
20019        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20020            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20021        }
20022
20023        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20024        try {
20025            final XmlSerializer serializer = new FastXmlSerializer();
20026            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20027            serializer.startDocument(null, true);
20028            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20029
20030            synchronized (mPackages) {
20031                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20032            }
20033
20034            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20035            serializer.endDocument();
20036            serializer.flush();
20037        } catch (Exception e) {
20038            if (DEBUG_BACKUP) {
20039                Slog.e(TAG, "Unable to write default apps for backup", e);
20040            }
20041            return null;
20042        }
20043
20044        return dataStream.toByteArray();
20045    }
20046
20047    @Override
20048    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20049        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20050            throw new SecurityException("Only the system may call restorePreferredActivities()");
20051        }
20052
20053        try {
20054            final XmlPullParser parser = Xml.newPullParser();
20055            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20056            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20057                    new BlobXmlRestorer() {
20058                        @Override
20059                        public void apply(XmlPullParser parser, int userId)
20060                                throws XmlPullParserException, IOException {
20061                            synchronized (mPackages) {
20062                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20063                                mSettings.writeLPr();
20064                            }
20065                        }
20066                    } );
20067        } catch (Exception e) {
20068            if (DEBUG_BACKUP) {
20069                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20070            }
20071        }
20072    }
20073
20074    @Override
20075    public byte[] getPermissionGrantBackup(int userId) {
20076        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20077            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20078        }
20079
20080        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20081        try {
20082            final XmlSerializer serializer = new FastXmlSerializer();
20083            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20084            serializer.startDocument(null, true);
20085            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20086
20087            synchronized (mPackages) {
20088                serializeRuntimePermissionGrantsLPr(serializer, userId);
20089            }
20090
20091            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20092            serializer.endDocument();
20093            serializer.flush();
20094        } catch (Exception e) {
20095            if (DEBUG_BACKUP) {
20096                Slog.e(TAG, "Unable to write default apps for backup", e);
20097            }
20098            return null;
20099        }
20100
20101        return dataStream.toByteArray();
20102    }
20103
20104    @Override
20105    public void restorePermissionGrants(byte[] backup, int userId) {
20106        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20107            throw new SecurityException("Only the system may call restorePermissionGrants()");
20108        }
20109
20110        try {
20111            final XmlPullParser parser = Xml.newPullParser();
20112            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20113            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20114                    new BlobXmlRestorer() {
20115                        @Override
20116                        public void apply(XmlPullParser parser, int userId)
20117                                throws XmlPullParserException, IOException {
20118                            synchronized (mPackages) {
20119                                processRestoredPermissionGrantsLPr(parser, userId);
20120                            }
20121                        }
20122                    } );
20123        } catch (Exception e) {
20124            if (DEBUG_BACKUP) {
20125                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20126            }
20127        }
20128    }
20129
20130    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20131            throws IOException {
20132        serializer.startTag(null, TAG_ALL_GRANTS);
20133
20134        final int N = mSettings.mPackages.size();
20135        for (int i = 0; i < N; i++) {
20136            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20137            boolean pkgGrantsKnown = false;
20138
20139            PermissionsState packagePerms = ps.getPermissionsState();
20140
20141            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20142                final int grantFlags = state.getFlags();
20143                // only look at grants that are not system/policy fixed
20144                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20145                    final boolean isGranted = state.isGranted();
20146                    // And only back up the user-twiddled state bits
20147                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20148                        final String packageName = mSettings.mPackages.keyAt(i);
20149                        if (!pkgGrantsKnown) {
20150                            serializer.startTag(null, TAG_GRANT);
20151                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20152                            pkgGrantsKnown = true;
20153                        }
20154
20155                        final boolean userSet =
20156                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20157                        final boolean userFixed =
20158                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20159                        final boolean revoke =
20160                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20161
20162                        serializer.startTag(null, TAG_PERMISSION);
20163                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20164                        if (isGranted) {
20165                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20166                        }
20167                        if (userSet) {
20168                            serializer.attribute(null, ATTR_USER_SET, "true");
20169                        }
20170                        if (userFixed) {
20171                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20172                        }
20173                        if (revoke) {
20174                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20175                        }
20176                        serializer.endTag(null, TAG_PERMISSION);
20177                    }
20178                }
20179            }
20180
20181            if (pkgGrantsKnown) {
20182                serializer.endTag(null, TAG_GRANT);
20183            }
20184        }
20185
20186        serializer.endTag(null, TAG_ALL_GRANTS);
20187    }
20188
20189    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20190            throws XmlPullParserException, IOException {
20191        String pkgName = null;
20192        int outerDepth = parser.getDepth();
20193        int type;
20194        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20195                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20196            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20197                continue;
20198            }
20199
20200            final String tagName = parser.getName();
20201            if (tagName.equals(TAG_GRANT)) {
20202                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20203                if (DEBUG_BACKUP) {
20204                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20205                }
20206            } else if (tagName.equals(TAG_PERMISSION)) {
20207
20208                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20209                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20210
20211                int newFlagSet = 0;
20212                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20213                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20214                }
20215                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20216                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20217                }
20218                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20219                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20220                }
20221                if (DEBUG_BACKUP) {
20222                    Slog.v(TAG, "  + Restoring grant:"
20223                            + " pkg=" + pkgName
20224                            + " perm=" + permName
20225                            + " granted=" + isGranted
20226                            + " bits=0x" + Integer.toHexString(newFlagSet));
20227                }
20228                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20229                if (ps != null) {
20230                    // Already installed so we apply the grant immediately
20231                    if (DEBUG_BACKUP) {
20232                        Slog.v(TAG, "        + already installed; applying");
20233                    }
20234                    PermissionsState perms = ps.getPermissionsState();
20235                    BasePermission bp =
20236                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20237                    if (bp != null) {
20238                        if (isGranted) {
20239                            perms.grantRuntimePermission(bp, userId);
20240                        }
20241                        if (newFlagSet != 0) {
20242                            perms.updatePermissionFlags(
20243                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20244                        }
20245                    }
20246                } else {
20247                    // Need to wait for post-restore install to apply the grant
20248                    if (DEBUG_BACKUP) {
20249                        Slog.v(TAG, "        - not yet installed; saving for later");
20250                    }
20251                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20252                            isGranted, newFlagSet, userId);
20253                }
20254            } else {
20255                PackageManagerService.reportSettingsProblem(Log.WARN,
20256                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20257                XmlUtils.skipCurrentTag(parser);
20258            }
20259        }
20260
20261        scheduleWriteSettingsLocked();
20262        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20263    }
20264
20265    @Override
20266    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20267            int sourceUserId, int targetUserId, int flags) {
20268        mContext.enforceCallingOrSelfPermission(
20269                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20270        int callingUid = Binder.getCallingUid();
20271        enforceOwnerRights(ownerPackage, callingUid);
20272        PackageManagerServiceUtils.enforceShellRestriction(
20273                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20274        if (intentFilter.countActions() == 0) {
20275            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20276            return;
20277        }
20278        synchronized (mPackages) {
20279            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20280                    ownerPackage, targetUserId, flags);
20281            CrossProfileIntentResolver resolver =
20282                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20283            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20284            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20285            if (existing != null) {
20286                int size = existing.size();
20287                for (int i = 0; i < size; i++) {
20288                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20289                        return;
20290                    }
20291                }
20292            }
20293            resolver.addFilter(newFilter);
20294            scheduleWritePackageRestrictionsLocked(sourceUserId);
20295        }
20296    }
20297
20298    @Override
20299    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20300        mContext.enforceCallingOrSelfPermission(
20301                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20302        final int callingUid = Binder.getCallingUid();
20303        enforceOwnerRights(ownerPackage, callingUid);
20304        PackageManagerServiceUtils.enforceShellRestriction(
20305                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20306        synchronized (mPackages) {
20307            CrossProfileIntentResolver resolver =
20308                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20309            ArraySet<CrossProfileIntentFilter> set =
20310                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20311            for (CrossProfileIntentFilter filter : set) {
20312                if (filter.getOwnerPackage().equals(ownerPackage)) {
20313                    resolver.removeFilter(filter);
20314                }
20315            }
20316            scheduleWritePackageRestrictionsLocked(sourceUserId);
20317        }
20318    }
20319
20320    // Enforcing that callingUid is owning pkg on userId
20321    private void enforceOwnerRights(String pkg, int callingUid) {
20322        // The system owns everything.
20323        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20324            return;
20325        }
20326        final int callingUserId = UserHandle.getUserId(callingUid);
20327        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20328        if (pi == null) {
20329            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20330                    + callingUserId);
20331        }
20332        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20333            throw new SecurityException("Calling uid " + callingUid
20334                    + " does not own package " + pkg);
20335        }
20336    }
20337
20338    @Override
20339    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20340        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20341            return null;
20342        }
20343        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20344    }
20345
20346    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20347        UserManagerService ums = UserManagerService.getInstance();
20348        if (ums != null) {
20349            final UserInfo parent = ums.getProfileParent(userId);
20350            final int launcherUid = (parent != null) ? parent.id : userId;
20351            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20352            if (launcherComponent != null) {
20353                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20354                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20355                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20356                        .setPackage(launcherComponent.getPackageName());
20357                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20358            }
20359        }
20360    }
20361
20362    /**
20363     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20364     * then reports the most likely home activity or null if there are more than one.
20365     */
20366    private ComponentName getDefaultHomeActivity(int userId) {
20367        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20368        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20369        if (cn != null) {
20370            return cn;
20371        }
20372
20373        // Find the launcher with the highest priority and return that component if there are no
20374        // other home activity with the same priority.
20375        int lastPriority = Integer.MIN_VALUE;
20376        ComponentName lastComponent = null;
20377        final int size = allHomeCandidates.size();
20378        for (int i = 0; i < size; i++) {
20379            final ResolveInfo ri = allHomeCandidates.get(i);
20380            if (ri.priority > lastPriority) {
20381                lastComponent = ri.activityInfo.getComponentName();
20382                lastPriority = ri.priority;
20383            } else if (ri.priority == lastPriority) {
20384                // Two components found with same priority.
20385                lastComponent = null;
20386            }
20387        }
20388        return lastComponent;
20389    }
20390
20391    private Intent getHomeIntent() {
20392        Intent intent = new Intent(Intent.ACTION_MAIN);
20393        intent.addCategory(Intent.CATEGORY_HOME);
20394        intent.addCategory(Intent.CATEGORY_DEFAULT);
20395        return intent;
20396    }
20397
20398    private IntentFilter getHomeFilter() {
20399        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20400        filter.addCategory(Intent.CATEGORY_HOME);
20401        filter.addCategory(Intent.CATEGORY_DEFAULT);
20402        return filter;
20403    }
20404
20405    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20406            int userId) {
20407        Intent intent  = getHomeIntent();
20408        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20409                PackageManager.GET_META_DATA, userId);
20410        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20411                true, false, false, userId);
20412
20413        allHomeCandidates.clear();
20414        if (list != null) {
20415            for (ResolveInfo ri : list) {
20416                allHomeCandidates.add(ri);
20417            }
20418        }
20419        return (preferred == null || preferred.activityInfo == null)
20420                ? null
20421                : new ComponentName(preferred.activityInfo.packageName,
20422                        preferred.activityInfo.name);
20423    }
20424
20425    @Override
20426    public void setHomeActivity(ComponentName comp, int userId) {
20427        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20428            return;
20429        }
20430        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20431        getHomeActivitiesAsUser(homeActivities, userId);
20432
20433        boolean found = false;
20434
20435        final int size = homeActivities.size();
20436        final ComponentName[] set = new ComponentName[size];
20437        for (int i = 0; i < size; i++) {
20438            final ResolveInfo candidate = homeActivities.get(i);
20439            final ActivityInfo info = candidate.activityInfo;
20440            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20441            set[i] = activityName;
20442            if (!found && activityName.equals(comp)) {
20443                found = true;
20444            }
20445        }
20446        if (!found) {
20447            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20448                    + userId);
20449        }
20450        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20451                set, comp, userId);
20452    }
20453
20454    private @Nullable String getSetupWizardPackageName() {
20455        final Intent intent = new Intent(Intent.ACTION_MAIN);
20456        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20457
20458        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20459                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20460                        | MATCH_DISABLED_COMPONENTS,
20461                UserHandle.myUserId());
20462        if (matches.size() == 1) {
20463            return matches.get(0).getComponentInfo().packageName;
20464        } else {
20465            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20466                    + ": matches=" + matches);
20467            return null;
20468        }
20469    }
20470
20471    private @Nullable String getStorageManagerPackageName() {
20472        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20473
20474        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20475                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20476                        | MATCH_DISABLED_COMPONENTS,
20477                UserHandle.myUserId());
20478        if (matches.size() == 1) {
20479            return matches.get(0).getComponentInfo().packageName;
20480        } else {
20481            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20482                    + matches.size() + ": matches=" + matches);
20483            return null;
20484        }
20485    }
20486
20487    @Override
20488    public String getSystemTextClassifierPackageName() {
20489        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20490    }
20491
20492    @Override
20493    public void setApplicationEnabledSetting(String appPackageName,
20494            int newState, int flags, int userId, String callingPackage) {
20495        if (!sUserManager.exists(userId)) return;
20496        if (callingPackage == null) {
20497            callingPackage = Integer.toString(Binder.getCallingUid());
20498        }
20499        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20500    }
20501
20502    @Override
20503    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20504        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20505        synchronized (mPackages) {
20506            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20507            if (pkgSetting != null) {
20508                pkgSetting.setUpdateAvailable(updateAvailable);
20509            }
20510        }
20511    }
20512
20513    @Override
20514    public void setComponentEnabledSetting(ComponentName componentName,
20515            int newState, int flags, int userId) {
20516        if (!sUserManager.exists(userId)) return;
20517        setEnabledSetting(componentName.getPackageName(),
20518                componentName.getClassName(), newState, flags, userId, null);
20519    }
20520
20521    private void setEnabledSetting(final String packageName, String className, int newState,
20522            final int flags, int userId, String callingPackage) {
20523        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20524              || newState == COMPONENT_ENABLED_STATE_ENABLED
20525              || newState == COMPONENT_ENABLED_STATE_DISABLED
20526              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20527              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20528            throw new IllegalArgumentException("Invalid new component state: "
20529                    + newState);
20530        }
20531        PackageSetting pkgSetting;
20532        final int callingUid = Binder.getCallingUid();
20533        final int permission;
20534        if (callingUid == Process.SYSTEM_UID) {
20535            permission = PackageManager.PERMISSION_GRANTED;
20536        } else {
20537            permission = mContext.checkCallingOrSelfPermission(
20538                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20539        }
20540        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20541                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20542        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20543        boolean sendNow = false;
20544        boolean isApp = (className == null);
20545        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20546        String componentName = isApp ? packageName : className;
20547        int packageUid = -1;
20548        ArrayList<String> components;
20549
20550        // reader
20551        synchronized (mPackages) {
20552            pkgSetting = mSettings.mPackages.get(packageName);
20553            if (pkgSetting == null) {
20554                if (!isCallerInstantApp) {
20555                    if (className == null) {
20556                        throw new IllegalArgumentException("Unknown package: " + packageName);
20557                    }
20558                    throw new IllegalArgumentException(
20559                            "Unknown component: " + packageName + "/" + className);
20560                } else {
20561                    // throw SecurityException to prevent leaking package information
20562                    throw new SecurityException(
20563                            "Attempt to change component state; "
20564                            + "pid=" + Binder.getCallingPid()
20565                            + ", uid=" + callingUid
20566                            + (className == null
20567                                    ? ", package=" + packageName
20568                                    : ", component=" + packageName + "/" + className));
20569                }
20570            }
20571        }
20572
20573        // Limit who can change which apps
20574        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20575            // Don't allow apps that don't have permission to modify other apps
20576            if (!allowedByPermission
20577                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20578                throw new SecurityException(
20579                        "Attempt to change component state; "
20580                        + "pid=" + Binder.getCallingPid()
20581                        + ", uid=" + callingUid
20582                        + (className == null
20583                                ? ", package=" + packageName
20584                                : ", component=" + packageName + "/" + className));
20585            }
20586            // Don't allow changing protected packages.
20587            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20588                throw new SecurityException("Cannot disable a protected package: " + packageName);
20589            }
20590        }
20591
20592        synchronized (mPackages) {
20593            if (callingUid == Process.SHELL_UID
20594                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20595                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20596                // unless it is a test package.
20597                int oldState = pkgSetting.getEnabled(userId);
20598                if (className == null
20599                        &&
20600                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20601                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20602                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20603                        &&
20604                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20605                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20606                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20607                    // ok
20608                } else {
20609                    throw new SecurityException(
20610                            "Shell cannot change component state for " + packageName + "/"
20611                                    + className + " to " + newState);
20612                }
20613            }
20614        }
20615        if (className == null) {
20616            // We're dealing with an application/package level state change
20617            synchronized (mPackages) {
20618                if (pkgSetting.getEnabled(userId) == newState) {
20619                    // Nothing to do
20620                    return;
20621                }
20622            }
20623            // If we're enabling a system stub, there's a little more work to do.
20624            // Prior to enabling the package, we need to decompress the APK(s) to the
20625            // data partition and then replace the version on the system partition.
20626            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20627            final boolean isSystemStub = deletedPkg.isStub
20628                    && deletedPkg.isSystem();
20629            if (isSystemStub
20630                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20631                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20632                final File codePath = decompressPackage(deletedPkg);
20633                if (codePath == null) {
20634                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20635                    return;
20636                }
20637                // TODO remove direct parsing of the package object during internal cleanup
20638                // of scan package
20639                // We need to call parse directly here for no other reason than we need
20640                // the new package in order to disable the old one [we use the information
20641                // for some internal optimization to optionally create a new package setting
20642                // object on replace]. However, we can't get the package from the scan
20643                // because the scan modifies live structures and we need to remove the
20644                // old [system] package from the system before a scan can be attempted.
20645                // Once scan is indempotent we can remove this parse and use the package
20646                // object we scanned, prior to adding it to package settings.
20647                final PackageParser pp = new PackageParser();
20648                pp.setSeparateProcesses(mSeparateProcesses);
20649                pp.setDisplayMetrics(mMetrics);
20650                pp.setCallback(mPackageParserCallback);
20651                final PackageParser.Package tmpPkg;
20652                try {
20653                    final @ParseFlags int parseFlags = mDefParseFlags
20654                            | PackageParser.PARSE_MUST_BE_APK
20655                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20656                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20657                } catch (PackageParserException e) {
20658                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20659                    return;
20660                }
20661                synchronized (mInstallLock) {
20662                    // Disable the stub and remove any package entries
20663                    removePackageLI(deletedPkg, true);
20664                    synchronized (mPackages) {
20665                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20666                    }
20667                    final PackageParser.Package pkg;
20668                    try (PackageFreezer freezer =
20669                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20670                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20671                                | PackageParser.PARSE_ENFORCE_CODE;
20672                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20673                                0 /*currentTime*/, null /*user*/);
20674                        prepareAppDataAfterInstallLIF(pkg);
20675                        synchronized (mPackages) {
20676                            try {
20677                                updateSharedLibrariesLPr(pkg, null);
20678                            } catch (PackageManagerException e) {
20679                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20680                            }
20681                            mPermissionManager.updatePermissions(
20682                                    pkg.packageName, pkg, true, mPackages.values(),
20683                                    mPermissionCallback);
20684                            mSettings.writeLPr();
20685                        }
20686                    } catch (PackageManagerException e) {
20687                        // Whoops! Something went wrong; try to roll back to the stub
20688                        Slog.w(TAG, "Failed to install compressed system package:"
20689                                + pkgSetting.name, e);
20690                        // Remove the failed install
20691                        removeCodePathLI(codePath);
20692
20693                        // Install the system package
20694                        try (PackageFreezer freezer =
20695                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20696                            synchronized (mPackages) {
20697                                // NOTE: The system package always needs to be enabled; even
20698                                // if it's for a compressed stub. If we don't, installing the
20699                                // system package fails during scan [scanning checks the disabled
20700                                // packages]. We will reverse this later, after we've "installed"
20701                                // the stub.
20702                                // This leaves us in a fragile state; the stub should never be
20703                                // enabled, so, cross your fingers and hope nothing goes wrong
20704                                // until we can disable the package later.
20705                                enableSystemPackageLPw(deletedPkg);
20706                            }
20707                            installPackageFromSystemLIF(deletedPkg.codePath,
20708                                    false /*isPrivileged*/, null /*allUserHandles*/,
20709                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20710                                    true /*writeSettings*/);
20711                        } catch (PackageManagerException pme) {
20712                            Slog.w(TAG, "Failed to restore system package:"
20713                                    + deletedPkg.packageName, pme);
20714                        } finally {
20715                            synchronized (mPackages) {
20716                                mSettings.disableSystemPackageLPw(
20717                                        deletedPkg.packageName, true /*replaced*/);
20718                                mSettings.writeLPr();
20719                            }
20720                        }
20721                        return;
20722                    }
20723                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20724                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20725                    mDexManager.notifyPackageUpdated(pkg.packageName,
20726                            pkg.baseCodePath, pkg.splitCodePaths);
20727                }
20728            }
20729            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20730                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20731                // Don't care about who enables an app.
20732                callingPackage = null;
20733            }
20734            synchronized (mPackages) {
20735                pkgSetting.setEnabled(newState, userId, callingPackage);
20736            }
20737        } else {
20738            synchronized (mPackages) {
20739                // We're dealing with a component level state change
20740                // First, verify that this is a valid class name.
20741                PackageParser.Package pkg = pkgSetting.pkg;
20742                if (pkg == null || !pkg.hasComponentClassName(className)) {
20743                    if (pkg != null &&
20744                            pkg.applicationInfo.targetSdkVersion >=
20745                                    Build.VERSION_CODES.JELLY_BEAN) {
20746                        throw new IllegalArgumentException("Component class " + className
20747                                + " does not exist in " + packageName);
20748                    } else {
20749                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20750                                + className + " does not exist in " + packageName);
20751                    }
20752                }
20753                switch (newState) {
20754                    case COMPONENT_ENABLED_STATE_ENABLED:
20755                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20756                            return;
20757                        }
20758                        break;
20759                    case COMPONENT_ENABLED_STATE_DISABLED:
20760                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20761                            return;
20762                        }
20763                        break;
20764                    case COMPONENT_ENABLED_STATE_DEFAULT:
20765                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20766                            return;
20767                        }
20768                        break;
20769                    default:
20770                        Slog.e(TAG, "Invalid new component state: " + newState);
20771                        return;
20772                }
20773            }
20774        }
20775        synchronized (mPackages) {
20776            scheduleWritePackageRestrictionsLocked(userId);
20777            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20778            final long callingId = Binder.clearCallingIdentity();
20779            try {
20780                updateInstantAppInstallerLocked(packageName);
20781            } finally {
20782                Binder.restoreCallingIdentity(callingId);
20783            }
20784            components = mPendingBroadcasts.get(userId, packageName);
20785            final boolean newPackage = components == null;
20786            if (newPackage) {
20787                components = new ArrayList<String>();
20788            }
20789            if (!components.contains(componentName)) {
20790                components.add(componentName);
20791            }
20792            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20793                sendNow = true;
20794                // Purge entry from pending broadcast list if another one exists already
20795                // since we are sending one right away.
20796                mPendingBroadcasts.remove(userId, packageName);
20797            } else {
20798                if (newPackage) {
20799                    mPendingBroadcasts.put(userId, packageName, components);
20800                }
20801                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20802                    // Schedule a message
20803                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20804                }
20805            }
20806        }
20807
20808        long callingId = Binder.clearCallingIdentity();
20809        try {
20810            if (sendNow) {
20811                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20812                sendPackageChangedBroadcast(packageName,
20813                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20814            }
20815        } finally {
20816            Binder.restoreCallingIdentity(callingId);
20817        }
20818    }
20819
20820    @Override
20821    public void flushPackageRestrictionsAsUser(int userId) {
20822        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20823            return;
20824        }
20825        if (!sUserManager.exists(userId)) {
20826            return;
20827        }
20828        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20829                false /* checkShell */, "flushPackageRestrictions");
20830        synchronized (mPackages) {
20831            mSettings.writePackageRestrictionsLPr(userId);
20832            mDirtyUsers.remove(userId);
20833            if (mDirtyUsers.isEmpty()) {
20834                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20835            }
20836        }
20837    }
20838
20839    private void sendPackageChangedBroadcast(String packageName,
20840            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20841        if (DEBUG_INSTALL)
20842            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20843                    + componentNames);
20844        Bundle extras = new Bundle(4);
20845        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20846        String nameList[] = new String[componentNames.size()];
20847        componentNames.toArray(nameList);
20848        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20849        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20850        extras.putInt(Intent.EXTRA_UID, packageUid);
20851        // If this is not reporting a change of the overall package, then only send it
20852        // to registered receivers.  We don't want to launch a swath of apps for every
20853        // little component state change.
20854        final int flags = !componentNames.contains(packageName)
20855                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20856        final int userId = UserHandle.getUserId(packageUid);
20857        final boolean isInstantApp = isInstantApp(packageName, userId);
20858        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20859        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20860        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20861                userIds, instantUserIds);
20862    }
20863
20864    @Override
20865    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20866        if (!sUserManager.exists(userId)) return;
20867        final int callingUid = Binder.getCallingUid();
20868        if (getInstantAppPackageName(callingUid) != null) {
20869            return;
20870        }
20871        final int permission = mContext.checkCallingOrSelfPermission(
20872                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20873        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20874        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20875                true /* requireFullPermission */, true /* checkShell */, "stop package");
20876        // writer
20877        synchronized (mPackages) {
20878            final PackageSetting ps = mSettings.mPackages.get(packageName);
20879            if (!filterAppAccessLPr(ps, callingUid, userId)
20880                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20881                            allowedByPermission, callingUid, userId)) {
20882                scheduleWritePackageRestrictionsLocked(userId);
20883            }
20884        }
20885    }
20886
20887    @Override
20888    public String getInstallerPackageName(String packageName) {
20889        final int callingUid = Binder.getCallingUid();
20890        synchronized (mPackages) {
20891            final PackageSetting ps = mSettings.mPackages.get(packageName);
20892            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20893                return null;
20894            }
20895            return mSettings.getInstallerPackageNameLPr(packageName);
20896        }
20897    }
20898
20899    public boolean isOrphaned(String packageName) {
20900        // reader
20901        synchronized (mPackages) {
20902            return mSettings.isOrphaned(packageName);
20903        }
20904    }
20905
20906    @Override
20907    public int getApplicationEnabledSetting(String packageName, int userId) {
20908        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20909        int callingUid = Binder.getCallingUid();
20910        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20911                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20912        // reader
20913        synchronized (mPackages) {
20914            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20915                return COMPONENT_ENABLED_STATE_DISABLED;
20916            }
20917            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20918        }
20919    }
20920
20921    @Override
20922    public int getComponentEnabledSetting(ComponentName component, int userId) {
20923        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20924        int callingUid = Binder.getCallingUid();
20925        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20926                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20927        synchronized (mPackages) {
20928            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20929                    component, TYPE_UNKNOWN, userId)) {
20930                return COMPONENT_ENABLED_STATE_DISABLED;
20931            }
20932            return mSettings.getComponentEnabledSettingLPr(component, userId);
20933        }
20934    }
20935
20936    @Override
20937    public void enterSafeMode() {
20938        enforceSystemOrRoot("Only the system can request entering safe mode");
20939
20940        if (!mSystemReady) {
20941            mSafeMode = true;
20942        }
20943    }
20944
20945    @Override
20946    public void systemReady() {
20947        enforceSystemOrRoot("Only the system can claim the system is ready");
20948
20949        mSystemReady = true;
20950        final ContentResolver resolver = mContext.getContentResolver();
20951        ContentObserver co = new ContentObserver(mHandler) {
20952            @Override
20953            public void onChange(boolean selfChange) {
20954                mWebInstantAppsDisabled =
20955                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20956                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20957            }
20958        };
20959        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20960                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20961                false, co, UserHandle.USER_SYSTEM);
20962        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20963                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20964        co.onChange(true);
20965
20966        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20967        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20968        // it is done.
20969        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20970            @Override
20971            public void onChange(boolean selfChange) {
20972                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20973                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20974                        oobEnabled == 1 ? "true" : "false");
20975            }
20976        };
20977        mContext.getContentResolver().registerContentObserver(
20978                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20979                UserHandle.USER_SYSTEM);
20980        // At boot, restore the value from the setting, which persists across reboot.
20981        privAppOobObserver.onChange(true);
20982
20983        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20984        // disabled after already being started.
20985        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20986                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20987
20988        // Read the compatibilty setting when the system is ready.
20989        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20990                mContext.getContentResolver(),
20991                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20992        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20993        if (DEBUG_SETTINGS) {
20994            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20995        }
20996
20997        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20998
20999        synchronized (mPackages) {
21000            // Verify that all of the preferred activity components actually
21001            // exist.  It is possible for applications to be updated and at
21002            // that point remove a previously declared activity component that
21003            // had been set as a preferred activity.  We try to clean this up
21004            // the next time we encounter that preferred activity, but it is
21005            // possible for the user flow to never be able to return to that
21006            // situation so here we do a sanity check to make sure we haven't
21007            // left any junk around.
21008            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21009            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21010                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21011                removed.clear();
21012                for (PreferredActivity pa : pir.filterSet()) {
21013                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21014                        removed.add(pa);
21015                    }
21016                }
21017                if (removed.size() > 0) {
21018                    for (int r=0; r<removed.size(); r++) {
21019                        PreferredActivity pa = removed.get(r);
21020                        Slog.w(TAG, "Removing dangling preferred activity: "
21021                                + pa.mPref.mComponent);
21022                        pir.removeFilter(pa);
21023                    }
21024                    mSettings.writePackageRestrictionsLPr(
21025                            mSettings.mPreferredActivities.keyAt(i));
21026                }
21027            }
21028
21029            for (int userId : UserManagerService.getInstance().getUserIds()) {
21030                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21031                    grantPermissionsUserIds = ArrayUtils.appendInt(
21032                            grantPermissionsUserIds, userId);
21033                }
21034            }
21035        }
21036        sUserManager.systemReady();
21037        // If we upgraded grant all default permissions before kicking off.
21038        for (int userId : grantPermissionsUserIds) {
21039            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21040        }
21041
21042        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21043            // If we did not grant default permissions, we preload from this the
21044            // default permission exceptions lazily to ensure we don't hit the
21045            // disk on a new user creation.
21046            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21047        }
21048
21049        // Now that we've scanned all packages, and granted any default
21050        // permissions, ensure permissions are updated. Beware of dragons if you
21051        // try optimizing this.
21052        synchronized (mPackages) {
21053            mPermissionManager.updateAllPermissions(
21054                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21055                    mPermissionCallback);
21056        }
21057
21058        // Kick off any messages waiting for system ready
21059        if (mPostSystemReadyMessages != null) {
21060            for (Message msg : mPostSystemReadyMessages) {
21061                msg.sendToTarget();
21062            }
21063            mPostSystemReadyMessages = null;
21064        }
21065
21066        // Watch for external volumes that come and go over time
21067        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21068        storage.registerListener(mStorageListener);
21069
21070        mInstallerService.systemReady();
21071        mPackageDexOptimizer.systemReady();
21072
21073        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21074                StorageManagerInternal.class);
21075        StorageManagerInternal.addExternalStoragePolicy(
21076                new StorageManagerInternal.ExternalStorageMountPolicy() {
21077            @Override
21078            public int getMountMode(int uid, String packageName) {
21079                if (Process.isIsolated(uid)) {
21080                    return Zygote.MOUNT_EXTERNAL_NONE;
21081                }
21082                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21083                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21084                }
21085                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21086                    return Zygote.MOUNT_EXTERNAL_READ;
21087                }
21088                return Zygote.MOUNT_EXTERNAL_WRITE;
21089            }
21090
21091            @Override
21092            public boolean hasExternalStorage(int uid, String packageName) {
21093                return true;
21094            }
21095        });
21096
21097        // Now that we're mostly running, clean up stale users and apps
21098        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21099        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21100
21101        mPermissionManager.systemReady();
21102
21103        if (mInstantAppResolverConnection != null) {
21104            mContext.registerReceiver(new BroadcastReceiver() {
21105                @Override
21106                public void onReceive(Context context, Intent intent) {
21107                    mInstantAppResolverConnection.optimisticBind();
21108                    mContext.unregisterReceiver(this);
21109                }
21110            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21111        }
21112    }
21113
21114    public void waitForAppDataPrepared() {
21115        if (mPrepareAppDataFuture == null) {
21116            return;
21117        }
21118        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21119        mPrepareAppDataFuture = null;
21120    }
21121
21122    @Override
21123    public boolean isSafeMode() {
21124        // allow instant applications
21125        return mSafeMode;
21126    }
21127
21128    @Override
21129    public boolean hasSystemUidErrors() {
21130        // allow instant applications
21131        return mHasSystemUidErrors;
21132    }
21133
21134    static String arrayToString(int[] array) {
21135        StringBuffer buf = new StringBuffer(128);
21136        buf.append('[');
21137        if (array != null) {
21138            for (int i=0; i<array.length; i++) {
21139                if (i > 0) buf.append(", ");
21140                buf.append(array[i]);
21141            }
21142        }
21143        buf.append(']');
21144        return buf.toString();
21145    }
21146
21147    @Override
21148    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21149            FileDescriptor err, String[] args, ShellCallback callback,
21150            ResultReceiver resultReceiver) {
21151        (new PackageManagerShellCommand(this)).exec(
21152                this, in, out, err, args, callback, resultReceiver);
21153    }
21154
21155    @Override
21156    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21157        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21158
21159        DumpState dumpState = new DumpState();
21160        boolean fullPreferred = false;
21161        boolean checkin = false;
21162
21163        String packageName = null;
21164        ArraySet<String> permissionNames = null;
21165
21166        int opti = 0;
21167        while (opti < args.length) {
21168            String opt = args[opti];
21169            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21170                break;
21171            }
21172            opti++;
21173
21174            if ("-a".equals(opt)) {
21175                // Right now we only know how to print all.
21176            } else if ("-h".equals(opt)) {
21177                pw.println("Package manager dump options:");
21178                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21179                pw.println("    --checkin: dump for a checkin");
21180                pw.println("    -f: print details of intent filters");
21181                pw.println("    -h: print this help");
21182                pw.println("  cmd may be one of:");
21183                pw.println("    l[ibraries]: list known shared libraries");
21184                pw.println("    f[eatures]: list device features");
21185                pw.println("    k[eysets]: print known keysets");
21186                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21187                pw.println("    perm[issions]: dump permissions");
21188                pw.println("    permission [name ...]: dump declaration and use of given permission");
21189                pw.println("    pref[erred]: print preferred package settings");
21190                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21191                pw.println("    prov[iders]: dump content providers");
21192                pw.println("    p[ackages]: dump installed packages");
21193                pw.println("    s[hared-users]: dump shared user IDs");
21194                pw.println("    m[essages]: print collected runtime messages");
21195                pw.println("    v[erifiers]: print package verifier info");
21196                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21197                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21198                pw.println("    version: print database version info");
21199                pw.println("    write: write current settings now");
21200                pw.println("    installs: details about install sessions");
21201                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21202                pw.println("    dexopt: dump dexopt state");
21203                pw.println("    compiler-stats: dump compiler statistics");
21204                pw.println("    service-permissions: dump permissions required by services");
21205                pw.println("    <package.name>: info about given package");
21206                return;
21207            } else if ("--checkin".equals(opt)) {
21208                checkin = true;
21209            } else if ("-f".equals(opt)) {
21210                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21211            } else if ("--proto".equals(opt)) {
21212                dumpProto(fd);
21213                return;
21214            } else {
21215                pw.println("Unknown argument: " + opt + "; use -h for help");
21216            }
21217        }
21218
21219        // Is the caller requesting to dump a particular piece of data?
21220        if (opti < args.length) {
21221            String cmd = args[opti];
21222            opti++;
21223            // Is this a package name?
21224            if ("android".equals(cmd) || cmd.contains(".")) {
21225                packageName = cmd;
21226                // When dumping a single package, we always dump all of its
21227                // filter information since the amount of data will be reasonable.
21228                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21229            } else if ("check-permission".equals(cmd)) {
21230                if (opti >= args.length) {
21231                    pw.println("Error: check-permission missing permission argument");
21232                    return;
21233                }
21234                String perm = args[opti];
21235                opti++;
21236                if (opti >= args.length) {
21237                    pw.println("Error: check-permission missing package argument");
21238                    return;
21239                }
21240
21241                String pkg = args[opti];
21242                opti++;
21243                int user = UserHandle.getUserId(Binder.getCallingUid());
21244                if (opti < args.length) {
21245                    try {
21246                        user = Integer.parseInt(args[opti]);
21247                    } catch (NumberFormatException e) {
21248                        pw.println("Error: check-permission user argument is not a number: "
21249                                + args[opti]);
21250                        return;
21251                    }
21252                }
21253
21254                // Normalize package name to handle renamed packages and static libs
21255                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21256
21257                pw.println(checkPermission(perm, pkg, user));
21258                return;
21259            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21260                dumpState.setDump(DumpState.DUMP_LIBS);
21261            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21262                dumpState.setDump(DumpState.DUMP_FEATURES);
21263            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21264                if (opti >= args.length) {
21265                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21266                            | DumpState.DUMP_SERVICE_RESOLVERS
21267                            | DumpState.DUMP_RECEIVER_RESOLVERS
21268                            | DumpState.DUMP_CONTENT_RESOLVERS);
21269                } else {
21270                    while (opti < args.length) {
21271                        String name = args[opti];
21272                        if ("a".equals(name) || "activity".equals(name)) {
21273                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21274                        } else if ("s".equals(name) || "service".equals(name)) {
21275                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21276                        } else if ("r".equals(name) || "receiver".equals(name)) {
21277                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21278                        } else if ("c".equals(name) || "content".equals(name)) {
21279                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21280                        } else {
21281                            pw.println("Error: unknown resolver table type: " + name);
21282                            return;
21283                        }
21284                        opti++;
21285                    }
21286                }
21287            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21288                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21289            } else if ("permission".equals(cmd)) {
21290                if (opti >= args.length) {
21291                    pw.println("Error: permission requires permission name");
21292                    return;
21293                }
21294                permissionNames = new ArraySet<>();
21295                while (opti < args.length) {
21296                    permissionNames.add(args[opti]);
21297                    opti++;
21298                }
21299                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21300                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21301            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21302                dumpState.setDump(DumpState.DUMP_PREFERRED);
21303            } else if ("preferred-xml".equals(cmd)) {
21304                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21305                if (opti < args.length && "--full".equals(args[opti])) {
21306                    fullPreferred = true;
21307                    opti++;
21308                }
21309            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21310                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21311            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21312                dumpState.setDump(DumpState.DUMP_PACKAGES);
21313            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21314                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21315            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21316                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21317            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21318                dumpState.setDump(DumpState.DUMP_MESSAGES);
21319            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21320                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21321            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21322                    || "intent-filter-verifiers".equals(cmd)) {
21323                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21324            } else if ("version".equals(cmd)) {
21325                dumpState.setDump(DumpState.DUMP_VERSION);
21326            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21327                dumpState.setDump(DumpState.DUMP_KEYSETS);
21328            } else if ("installs".equals(cmd)) {
21329                dumpState.setDump(DumpState.DUMP_INSTALLS);
21330            } else if ("frozen".equals(cmd)) {
21331                dumpState.setDump(DumpState.DUMP_FROZEN);
21332            } else if ("volumes".equals(cmd)) {
21333                dumpState.setDump(DumpState.DUMP_VOLUMES);
21334            } else if ("dexopt".equals(cmd)) {
21335                dumpState.setDump(DumpState.DUMP_DEXOPT);
21336            } else if ("compiler-stats".equals(cmd)) {
21337                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21338            } else if ("changes".equals(cmd)) {
21339                dumpState.setDump(DumpState.DUMP_CHANGES);
21340            } else if ("service-permissions".equals(cmd)) {
21341                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21342            } else if ("write".equals(cmd)) {
21343                synchronized (mPackages) {
21344                    mSettings.writeLPr();
21345                    pw.println("Settings written.");
21346                    return;
21347                }
21348            }
21349        }
21350
21351        if (checkin) {
21352            pw.println("vers,1");
21353        }
21354
21355        // reader
21356        synchronized (mPackages) {
21357            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21358                if (!checkin) {
21359                    if (dumpState.onTitlePrinted())
21360                        pw.println();
21361                    pw.println("Database versions:");
21362                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21363                }
21364            }
21365
21366            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21367                if (!checkin) {
21368                    if (dumpState.onTitlePrinted())
21369                        pw.println();
21370                    pw.println("Verifiers:");
21371                    pw.print("  Required: ");
21372                    pw.print(mRequiredVerifierPackage);
21373                    pw.print(" (uid=");
21374                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21375                            UserHandle.USER_SYSTEM));
21376                    pw.println(")");
21377                } else if (mRequiredVerifierPackage != null) {
21378                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21379                    pw.print(",");
21380                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21381                            UserHandle.USER_SYSTEM));
21382                }
21383            }
21384
21385            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21386                    packageName == null) {
21387                if (mIntentFilterVerifierComponent != null) {
21388                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21389                    if (!checkin) {
21390                        if (dumpState.onTitlePrinted())
21391                            pw.println();
21392                        pw.println("Intent Filter Verifier:");
21393                        pw.print("  Using: ");
21394                        pw.print(verifierPackageName);
21395                        pw.print(" (uid=");
21396                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21397                                UserHandle.USER_SYSTEM));
21398                        pw.println(")");
21399                    } else if (verifierPackageName != null) {
21400                        pw.print("ifv,"); pw.print(verifierPackageName);
21401                        pw.print(",");
21402                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21403                                UserHandle.USER_SYSTEM));
21404                    }
21405                } else {
21406                    pw.println();
21407                    pw.println("No Intent Filter Verifier available!");
21408                }
21409            }
21410
21411            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21412                boolean printedHeader = false;
21413                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21414                while (it.hasNext()) {
21415                    String libName = it.next();
21416                    LongSparseArray<SharedLibraryEntry> versionedLib
21417                            = mSharedLibraries.get(libName);
21418                    if (versionedLib == null) {
21419                        continue;
21420                    }
21421                    final int versionCount = versionedLib.size();
21422                    for (int i = 0; i < versionCount; i++) {
21423                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21424                        if (!checkin) {
21425                            if (!printedHeader) {
21426                                if (dumpState.onTitlePrinted())
21427                                    pw.println();
21428                                pw.println("Libraries:");
21429                                printedHeader = true;
21430                            }
21431                            pw.print("  ");
21432                        } else {
21433                            pw.print("lib,");
21434                        }
21435                        pw.print(libEntry.info.getName());
21436                        if (libEntry.info.isStatic()) {
21437                            pw.print(" version=" + libEntry.info.getLongVersion());
21438                        }
21439                        if (!checkin) {
21440                            pw.print(" -> ");
21441                        }
21442                        if (libEntry.path != null) {
21443                            pw.print(" (jar) ");
21444                            pw.print(libEntry.path);
21445                        } else {
21446                            pw.print(" (apk) ");
21447                            pw.print(libEntry.apk);
21448                        }
21449                        pw.println();
21450                    }
21451                }
21452            }
21453
21454            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21455                if (dumpState.onTitlePrinted())
21456                    pw.println();
21457                if (!checkin) {
21458                    pw.println("Features:");
21459                }
21460
21461                synchronized (mAvailableFeatures) {
21462                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21463                        if (checkin) {
21464                            pw.print("feat,");
21465                            pw.print(feat.name);
21466                            pw.print(",");
21467                            pw.println(feat.version);
21468                        } else {
21469                            pw.print("  ");
21470                            pw.print(feat.name);
21471                            if (feat.version > 0) {
21472                                pw.print(" version=");
21473                                pw.print(feat.version);
21474                            }
21475                            pw.println();
21476                        }
21477                    }
21478                }
21479            }
21480
21481            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21482                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21483                        : "Activity Resolver Table:", "  ", packageName,
21484                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21485                    dumpState.setTitlePrinted(true);
21486                }
21487            }
21488            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21489                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21490                        : "Receiver Resolver Table:", "  ", packageName,
21491                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21492                    dumpState.setTitlePrinted(true);
21493                }
21494            }
21495            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21496                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21497                        : "Service Resolver Table:", "  ", packageName,
21498                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21499                    dumpState.setTitlePrinted(true);
21500                }
21501            }
21502            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21503                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21504                        : "Provider Resolver Table:", "  ", packageName,
21505                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21506                    dumpState.setTitlePrinted(true);
21507                }
21508            }
21509
21510            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21511                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21512                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21513                    int user = mSettings.mPreferredActivities.keyAt(i);
21514                    if (pir.dump(pw,
21515                            dumpState.getTitlePrinted()
21516                                ? "\nPreferred Activities User " + user + ":"
21517                                : "Preferred Activities User " + user + ":", "  ",
21518                            packageName, true, false)) {
21519                        dumpState.setTitlePrinted(true);
21520                    }
21521                }
21522            }
21523
21524            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21525                pw.flush();
21526                FileOutputStream fout = new FileOutputStream(fd);
21527                BufferedOutputStream str = new BufferedOutputStream(fout);
21528                XmlSerializer serializer = new FastXmlSerializer();
21529                try {
21530                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21531                    serializer.startDocument(null, true);
21532                    serializer.setFeature(
21533                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21534                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21535                    serializer.endDocument();
21536                    serializer.flush();
21537                } catch (IllegalArgumentException e) {
21538                    pw.println("Failed writing: " + e);
21539                } catch (IllegalStateException e) {
21540                    pw.println("Failed writing: " + e);
21541                } catch (IOException e) {
21542                    pw.println("Failed writing: " + e);
21543                }
21544            }
21545
21546            if (!checkin
21547                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21548                    && packageName == null) {
21549                pw.println();
21550                int count = mSettings.mPackages.size();
21551                if (count == 0) {
21552                    pw.println("No applications!");
21553                    pw.println();
21554                } else {
21555                    final String prefix = "  ";
21556                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21557                    if (allPackageSettings.size() == 0) {
21558                        pw.println("No domain preferred apps!");
21559                        pw.println();
21560                    } else {
21561                        pw.println("App verification status:");
21562                        pw.println();
21563                        count = 0;
21564                        for (PackageSetting ps : allPackageSettings) {
21565                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21566                            if (ivi == null || ivi.getPackageName() == null) continue;
21567                            pw.println(prefix + "Package: " + ivi.getPackageName());
21568                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21569                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21570                            pw.println();
21571                            count++;
21572                        }
21573                        if (count == 0) {
21574                            pw.println(prefix + "No app verification established.");
21575                            pw.println();
21576                        }
21577                        for (int userId : sUserManager.getUserIds()) {
21578                            pw.println("App linkages for user " + userId + ":");
21579                            pw.println();
21580                            count = 0;
21581                            for (PackageSetting ps : allPackageSettings) {
21582                                final long status = ps.getDomainVerificationStatusForUser(userId);
21583                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21584                                        && !DEBUG_DOMAIN_VERIFICATION) {
21585                                    continue;
21586                                }
21587                                pw.println(prefix + "Package: " + ps.name);
21588                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21589                                String statusStr = IntentFilterVerificationInfo.
21590                                        getStatusStringFromValue(status);
21591                                pw.println(prefix + "Status:  " + statusStr);
21592                                pw.println();
21593                                count++;
21594                            }
21595                            if (count == 0) {
21596                                pw.println(prefix + "No configured app linkages.");
21597                                pw.println();
21598                            }
21599                        }
21600                    }
21601                }
21602            }
21603
21604            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21605                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21606            }
21607
21608            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21609                boolean printedSomething = false;
21610                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21611                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21612                        continue;
21613                    }
21614                    if (!printedSomething) {
21615                        if (dumpState.onTitlePrinted())
21616                            pw.println();
21617                        pw.println("Registered ContentProviders:");
21618                        printedSomething = true;
21619                    }
21620                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21621                    pw.print("    "); pw.println(p.toString());
21622                }
21623                printedSomething = false;
21624                for (Map.Entry<String, PackageParser.Provider> entry :
21625                        mProvidersByAuthority.entrySet()) {
21626                    PackageParser.Provider p = entry.getValue();
21627                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21628                        continue;
21629                    }
21630                    if (!printedSomething) {
21631                        if (dumpState.onTitlePrinted())
21632                            pw.println();
21633                        pw.println("ContentProvider Authorities:");
21634                        printedSomething = true;
21635                    }
21636                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21637                    pw.print("    "); pw.println(p.toString());
21638                    if (p.info != null && p.info.applicationInfo != null) {
21639                        final String appInfo = p.info.applicationInfo.toString();
21640                        pw.print("      applicationInfo="); pw.println(appInfo);
21641                    }
21642                }
21643            }
21644
21645            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21646                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21647            }
21648
21649            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21650                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21651            }
21652
21653            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21654                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21655            }
21656
21657            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21658                if (dumpState.onTitlePrinted()) pw.println();
21659                pw.println("Package Changes:");
21660                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21661                final int K = mChangedPackages.size();
21662                for (int i = 0; i < K; i++) {
21663                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21664                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21665                    final int N = changes.size();
21666                    if (N == 0) {
21667                        pw.print("    "); pw.println("No packages changed");
21668                    } else {
21669                        for (int j = 0; j < N; j++) {
21670                            final String pkgName = changes.valueAt(j);
21671                            final int sequenceNumber = changes.keyAt(j);
21672                            pw.print("    ");
21673                            pw.print("seq=");
21674                            pw.print(sequenceNumber);
21675                            pw.print(", package=");
21676                            pw.println(pkgName);
21677                        }
21678                    }
21679                }
21680            }
21681
21682            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21683                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21684            }
21685
21686            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21687                // XXX should handle packageName != null by dumping only install data that
21688                // the given package is involved with.
21689                if (dumpState.onTitlePrinted()) pw.println();
21690
21691                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21692                ipw.println();
21693                ipw.println("Frozen packages:");
21694                ipw.increaseIndent();
21695                if (mFrozenPackages.size() == 0) {
21696                    ipw.println("(none)");
21697                } else {
21698                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21699                        ipw.println(mFrozenPackages.valueAt(i));
21700                    }
21701                }
21702                ipw.decreaseIndent();
21703            }
21704
21705            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21706                if (dumpState.onTitlePrinted()) pw.println();
21707
21708                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21709                ipw.println();
21710                ipw.println("Loaded volumes:");
21711                ipw.increaseIndent();
21712                if (mLoadedVolumes.size() == 0) {
21713                    ipw.println("(none)");
21714                } else {
21715                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21716                        ipw.println(mLoadedVolumes.valueAt(i));
21717                    }
21718                }
21719                ipw.decreaseIndent();
21720            }
21721
21722            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21723                    && packageName == null) {
21724                if (dumpState.onTitlePrinted()) pw.println();
21725                pw.println("Service permissions:");
21726
21727                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21728                while (filterIterator.hasNext()) {
21729                    final ServiceIntentInfo info = filterIterator.next();
21730                    final ServiceInfo serviceInfo = info.service.info;
21731                    final String permission = serviceInfo.permission;
21732                    if (permission != null) {
21733                        pw.print("    ");
21734                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21735                        pw.print(": ");
21736                        pw.println(permission);
21737                    }
21738                }
21739            }
21740
21741            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21742                if (dumpState.onTitlePrinted()) pw.println();
21743                dumpDexoptStateLPr(pw, packageName);
21744            }
21745
21746            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21747                if (dumpState.onTitlePrinted()) pw.println();
21748                dumpCompilerStatsLPr(pw, packageName);
21749            }
21750
21751            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21752                if (dumpState.onTitlePrinted()) pw.println();
21753                mSettings.dumpReadMessagesLPr(pw, dumpState);
21754
21755                pw.println();
21756                pw.println("Package warning messages:");
21757                dumpCriticalInfo(pw, null);
21758            }
21759
21760            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21761                dumpCriticalInfo(pw, "msg,");
21762            }
21763        }
21764
21765        // PackageInstaller should be called outside of mPackages lock
21766        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21767            // XXX should handle packageName != null by dumping only install data that
21768            // the given package is involved with.
21769            if (dumpState.onTitlePrinted()) pw.println();
21770            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21771        }
21772    }
21773
21774    private void dumpProto(FileDescriptor fd) {
21775        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21776
21777        synchronized (mPackages) {
21778            final long requiredVerifierPackageToken =
21779                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21780            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21781            proto.write(
21782                    PackageServiceDumpProto.PackageShortProto.UID,
21783                    getPackageUid(
21784                            mRequiredVerifierPackage,
21785                            MATCH_DEBUG_TRIAGED_MISSING,
21786                            UserHandle.USER_SYSTEM));
21787            proto.end(requiredVerifierPackageToken);
21788
21789            if (mIntentFilterVerifierComponent != null) {
21790                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21791                final long verifierPackageToken =
21792                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21793                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21794                proto.write(
21795                        PackageServiceDumpProto.PackageShortProto.UID,
21796                        getPackageUid(
21797                                verifierPackageName,
21798                                MATCH_DEBUG_TRIAGED_MISSING,
21799                                UserHandle.USER_SYSTEM));
21800                proto.end(verifierPackageToken);
21801            }
21802
21803            dumpSharedLibrariesProto(proto);
21804            dumpFeaturesProto(proto);
21805            mSettings.dumpPackagesProto(proto);
21806            mSettings.dumpSharedUsersProto(proto);
21807            dumpCriticalInfo(proto);
21808        }
21809        proto.flush();
21810    }
21811
21812    private void dumpFeaturesProto(ProtoOutputStream proto) {
21813        synchronized (mAvailableFeatures) {
21814            final int count = mAvailableFeatures.size();
21815            for (int i = 0; i < count; i++) {
21816                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21817            }
21818        }
21819    }
21820
21821    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21822        final int count = mSharedLibraries.size();
21823        for (int i = 0; i < count; i++) {
21824            final String libName = mSharedLibraries.keyAt(i);
21825            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21826            if (versionedLib == null) {
21827                continue;
21828            }
21829            final int versionCount = versionedLib.size();
21830            for (int j = 0; j < versionCount; j++) {
21831                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21832                final long sharedLibraryToken =
21833                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21834                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21835                final boolean isJar = (libEntry.path != null);
21836                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21837                if (isJar) {
21838                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21839                } else {
21840                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21841                }
21842                proto.end(sharedLibraryToken);
21843            }
21844        }
21845    }
21846
21847    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21848        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21849        ipw.println();
21850        ipw.println("Dexopt state:");
21851        ipw.increaseIndent();
21852        Collection<PackageParser.Package> packages = null;
21853        if (packageName != null) {
21854            PackageParser.Package targetPackage = mPackages.get(packageName);
21855            if (targetPackage != null) {
21856                packages = Collections.singletonList(targetPackage);
21857            } else {
21858                ipw.println("Unable to find package: " + packageName);
21859                return;
21860            }
21861        } else {
21862            packages = mPackages.values();
21863        }
21864
21865        for (PackageParser.Package pkg : packages) {
21866            ipw.println("[" + pkg.packageName + "]");
21867            ipw.increaseIndent();
21868            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21869                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21870            ipw.decreaseIndent();
21871        }
21872    }
21873
21874    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21875        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21876        ipw.println();
21877        ipw.println("Compiler stats:");
21878        ipw.increaseIndent();
21879        Collection<PackageParser.Package> packages = null;
21880        if (packageName != null) {
21881            PackageParser.Package targetPackage = mPackages.get(packageName);
21882            if (targetPackage != null) {
21883                packages = Collections.singletonList(targetPackage);
21884            } else {
21885                ipw.println("Unable to find package: " + packageName);
21886                return;
21887            }
21888        } else {
21889            packages = mPackages.values();
21890        }
21891
21892        for (PackageParser.Package pkg : packages) {
21893            ipw.println("[" + pkg.packageName + "]");
21894            ipw.increaseIndent();
21895
21896            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21897            if (stats == null) {
21898                ipw.println("(No recorded stats)");
21899            } else {
21900                stats.dump(ipw);
21901            }
21902            ipw.decreaseIndent();
21903        }
21904    }
21905
21906    private String dumpDomainString(String packageName) {
21907        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21908                .getList();
21909        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21910
21911        ArraySet<String> result = new ArraySet<>();
21912        if (iviList.size() > 0) {
21913            for (IntentFilterVerificationInfo ivi : iviList) {
21914                for (String host : ivi.getDomains()) {
21915                    result.add(host);
21916                }
21917            }
21918        }
21919        if (filters != null && filters.size() > 0) {
21920            for (IntentFilter filter : filters) {
21921                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21922                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21923                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21924                    result.addAll(filter.getHostsList());
21925                }
21926            }
21927        }
21928
21929        StringBuilder sb = new StringBuilder(result.size() * 16);
21930        for (String domain : result) {
21931            if (sb.length() > 0) sb.append(" ");
21932            sb.append(domain);
21933        }
21934        return sb.toString();
21935    }
21936
21937    // ------- apps on sdcard specific code -------
21938    static final boolean DEBUG_SD_INSTALL = false;
21939
21940    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21941
21942    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21943
21944    private boolean mMediaMounted = false;
21945
21946    static String getEncryptKey() {
21947        try {
21948            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21949                    SD_ENCRYPTION_KEYSTORE_NAME);
21950            if (sdEncKey == null) {
21951                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21952                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21953                if (sdEncKey == null) {
21954                    Slog.e(TAG, "Failed to create encryption keys");
21955                    return null;
21956                }
21957            }
21958            return sdEncKey;
21959        } catch (NoSuchAlgorithmException nsae) {
21960            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21961            return null;
21962        } catch (IOException ioe) {
21963            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21964            return null;
21965        }
21966    }
21967
21968    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21969            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21970        final int size = infos.size();
21971        final String[] packageNames = new String[size];
21972        final int[] packageUids = new int[size];
21973        for (int i = 0; i < size; i++) {
21974            final ApplicationInfo info = infos.get(i);
21975            packageNames[i] = info.packageName;
21976            packageUids[i] = info.uid;
21977        }
21978        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21979                finishedReceiver);
21980    }
21981
21982    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21983            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21984        sendResourcesChangedBroadcast(mediaStatus, replacing,
21985                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21986    }
21987
21988    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21989            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21990        int size = pkgList.length;
21991        if (size > 0) {
21992            // Send broadcasts here
21993            Bundle extras = new Bundle();
21994            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21995            if (uidArr != null) {
21996                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21997            }
21998            if (replacing) {
21999                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22000            }
22001            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22002                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22003            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22004        }
22005    }
22006
22007    private void loadPrivatePackages(final VolumeInfo vol) {
22008        mHandler.post(new Runnable() {
22009            @Override
22010            public void run() {
22011                loadPrivatePackagesInner(vol);
22012            }
22013        });
22014    }
22015
22016    private void loadPrivatePackagesInner(VolumeInfo vol) {
22017        final String volumeUuid = vol.fsUuid;
22018        if (TextUtils.isEmpty(volumeUuid)) {
22019            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22020            return;
22021        }
22022
22023        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22024        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22025        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22026
22027        final VersionInfo ver;
22028        final List<PackageSetting> packages;
22029        synchronized (mPackages) {
22030            ver = mSettings.findOrCreateVersion(volumeUuid);
22031            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22032        }
22033
22034        for (PackageSetting ps : packages) {
22035            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22036            synchronized (mInstallLock) {
22037                final PackageParser.Package pkg;
22038                try {
22039                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22040                    loaded.add(pkg.applicationInfo);
22041
22042                } catch (PackageManagerException e) {
22043                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22044                }
22045
22046                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22047                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22048                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22049                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22050                }
22051            }
22052        }
22053
22054        // Reconcile app data for all started/unlocked users
22055        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22056        final UserManager um = mContext.getSystemService(UserManager.class);
22057        UserManagerInternal umInternal = getUserManagerInternal();
22058        for (UserInfo user : um.getUsers()) {
22059            final int flags;
22060            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22061                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22062            } else if (umInternal.isUserRunning(user.id)) {
22063                flags = StorageManager.FLAG_STORAGE_DE;
22064            } else {
22065                continue;
22066            }
22067
22068            try {
22069                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22070                synchronized (mInstallLock) {
22071                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22072                }
22073            } catch (IllegalStateException e) {
22074                // Device was probably ejected, and we'll process that event momentarily
22075                Slog.w(TAG, "Failed to prepare storage: " + e);
22076            }
22077        }
22078
22079        synchronized (mPackages) {
22080            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22081            if (sdkUpdated) {
22082                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22083                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22084            }
22085            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22086                    mPermissionCallback);
22087
22088            // Yay, everything is now upgraded
22089            ver.forceCurrent();
22090
22091            mSettings.writeLPr();
22092        }
22093
22094        for (PackageFreezer freezer : freezers) {
22095            freezer.close();
22096        }
22097
22098        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22099        sendResourcesChangedBroadcast(true, false, loaded, null);
22100        mLoadedVolumes.add(vol.getId());
22101    }
22102
22103    private void unloadPrivatePackages(final VolumeInfo vol) {
22104        mHandler.post(new Runnable() {
22105            @Override
22106            public void run() {
22107                unloadPrivatePackagesInner(vol);
22108            }
22109        });
22110    }
22111
22112    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22113        final String volumeUuid = vol.fsUuid;
22114        if (TextUtils.isEmpty(volumeUuid)) {
22115            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22116            return;
22117        }
22118
22119        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22120        synchronized (mInstallLock) {
22121        synchronized (mPackages) {
22122            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22123            for (PackageSetting ps : packages) {
22124                if (ps.pkg == null) continue;
22125
22126                final ApplicationInfo info = ps.pkg.applicationInfo;
22127                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22128                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22129
22130                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22131                        "unloadPrivatePackagesInner")) {
22132                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22133                            false, null)) {
22134                        unloaded.add(info);
22135                    } else {
22136                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22137                    }
22138                }
22139
22140                // Try very hard to release any references to this package
22141                // so we don't risk the system server being killed due to
22142                // open FDs
22143                AttributeCache.instance().removePackage(ps.name);
22144            }
22145
22146            mSettings.writeLPr();
22147        }
22148        }
22149
22150        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22151        sendResourcesChangedBroadcast(false, false, unloaded, null);
22152        mLoadedVolumes.remove(vol.getId());
22153
22154        // Try very hard to release any references to this path so we don't risk
22155        // the system server being killed due to open FDs
22156        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22157
22158        for (int i = 0; i < 3; i++) {
22159            System.gc();
22160            System.runFinalization();
22161        }
22162    }
22163
22164    private void assertPackageKnown(String volumeUuid, String packageName)
22165            throws PackageManagerException {
22166        synchronized (mPackages) {
22167            // Normalize package name to handle renamed packages
22168            packageName = normalizePackageNameLPr(packageName);
22169
22170            final PackageSetting ps = mSettings.mPackages.get(packageName);
22171            if (ps == null) {
22172                throw new PackageManagerException("Package " + packageName + " is unknown");
22173            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22174                throw new PackageManagerException(
22175                        "Package " + packageName + " found on unknown volume " + volumeUuid
22176                                + "; expected volume " + ps.volumeUuid);
22177            }
22178        }
22179    }
22180
22181    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22182            throws PackageManagerException {
22183        synchronized (mPackages) {
22184            // Normalize package name to handle renamed packages
22185            packageName = normalizePackageNameLPr(packageName);
22186
22187            final PackageSetting ps = mSettings.mPackages.get(packageName);
22188            if (ps == null) {
22189                throw new PackageManagerException("Package " + packageName + " is unknown");
22190            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22191                throw new PackageManagerException(
22192                        "Package " + packageName + " found on unknown volume " + volumeUuid
22193                                + "; expected volume " + ps.volumeUuid);
22194            } else if (!ps.getInstalled(userId)) {
22195                throw new PackageManagerException(
22196                        "Package " + packageName + " not installed for user " + userId);
22197            }
22198        }
22199    }
22200
22201    private List<String> collectAbsoluteCodePaths() {
22202        synchronized (mPackages) {
22203            List<String> codePaths = new ArrayList<>();
22204            final int packageCount = mSettings.mPackages.size();
22205            for (int i = 0; i < packageCount; i++) {
22206                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22207                codePaths.add(ps.codePath.getAbsolutePath());
22208            }
22209            return codePaths;
22210        }
22211    }
22212
22213    /**
22214     * Examine all apps present on given mounted volume, and destroy apps that
22215     * aren't expected, either due to uninstallation or reinstallation on
22216     * another volume.
22217     */
22218    private void reconcileApps(String volumeUuid) {
22219        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22220        List<File> filesToDelete = null;
22221
22222        final File[] files = FileUtils.listFilesOrEmpty(
22223                Environment.getDataAppDirectory(volumeUuid));
22224        for (File file : files) {
22225            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22226                    && !PackageInstallerService.isStageName(file.getName());
22227            if (!isPackage) {
22228                // Ignore entries which are not packages
22229                continue;
22230            }
22231
22232            String absolutePath = file.getAbsolutePath();
22233
22234            boolean pathValid = false;
22235            final int absoluteCodePathCount = absoluteCodePaths.size();
22236            for (int i = 0; i < absoluteCodePathCount; i++) {
22237                String absoluteCodePath = absoluteCodePaths.get(i);
22238                if (absolutePath.startsWith(absoluteCodePath)) {
22239                    pathValid = true;
22240                    break;
22241                }
22242            }
22243
22244            if (!pathValid) {
22245                if (filesToDelete == null) {
22246                    filesToDelete = new ArrayList<>();
22247                }
22248                filesToDelete.add(file);
22249            }
22250        }
22251
22252        if (filesToDelete != null) {
22253            final int fileToDeleteCount = filesToDelete.size();
22254            for (int i = 0; i < fileToDeleteCount; i++) {
22255                File fileToDelete = filesToDelete.get(i);
22256                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22257                synchronized (mInstallLock) {
22258                    removeCodePathLI(fileToDelete);
22259                }
22260            }
22261        }
22262    }
22263
22264    /**
22265     * Reconcile all app data for the given user.
22266     * <p>
22267     * Verifies that directories exist and that ownership and labeling is
22268     * correct for all installed apps on all mounted volumes.
22269     */
22270    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22271        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22272        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22273            final String volumeUuid = vol.getFsUuid();
22274            synchronized (mInstallLock) {
22275                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22276            }
22277        }
22278    }
22279
22280    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22281            boolean migrateAppData) {
22282        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22283    }
22284
22285    /**
22286     * Reconcile all app data on given mounted volume.
22287     * <p>
22288     * Destroys app data that isn't expected, either due to uninstallation or
22289     * reinstallation on another volume.
22290     * <p>
22291     * Verifies that directories exist and that ownership and labeling is
22292     * correct for all installed apps.
22293     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22294     */
22295    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22296            boolean migrateAppData, boolean onlyCoreApps) {
22297        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22298                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22299        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22300
22301        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22302        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22303
22304        // First look for stale data that doesn't belong, and check if things
22305        // have changed since we did our last restorecon
22306        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22307            if (StorageManager.isFileEncryptedNativeOrEmulated()
22308                    && !StorageManager.isUserKeyUnlocked(userId)) {
22309                throw new RuntimeException(
22310                        "Yikes, someone asked us to reconcile CE storage while " + userId
22311                                + " was still locked; this would have caused massive data loss!");
22312            }
22313
22314            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22315            for (File file : files) {
22316                final String packageName = file.getName();
22317                try {
22318                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22319                } catch (PackageManagerException e) {
22320                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22321                    try {
22322                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22323                                StorageManager.FLAG_STORAGE_CE, 0);
22324                    } catch (InstallerException e2) {
22325                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22326                    }
22327                }
22328            }
22329        }
22330        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22331            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22332            for (File file : files) {
22333                final String packageName = file.getName();
22334                try {
22335                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22336                } catch (PackageManagerException e) {
22337                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22338                    try {
22339                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22340                                StorageManager.FLAG_STORAGE_DE, 0);
22341                    } catch (InstallerException e2) {
22342                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22343                    }
22344                }
22345            }
22346        }
22347
22348        // Ensure that data directories are ready to roll for all packages
22349        // installed for this volume and user
22350        final List<PackageSetting> packages;
22351        synchronized (mPackages) {
22352            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22353        }
22354        int preparedCount = 0;
22355        for (PackageSetting ps : packages) {
22356            final String packageName = ps.name;
22357            if (ps.pkg == null) {
22358                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22359                // TODO: might be due to legacy ASEC apps; we should circle back
22360                // and reconcile again once they're scanned
22361                continue;
22362            }
22363            // Skip non-core apps if requested
22364            if (onlyCoreApps && !ps.pkg.coreApp) {
22365                result.add(packageName);
22366                continue;
22367            }
22368
22369            if (ps.getInstalled(userId)) {
22370                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22371                preparedCount++;
22372            }
22373        }
22374
22375        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22376        return result;
22377    }
22378
22379    /**
22380     * Prepare app data for the given app just after it was installed or
22381     * upgraded. This method carefully only touches users that it's installed
22382     * for, and it forces a restorecon to handle any seinfo changes.
22383     * <p>
22384     * Verifies that directories exist and that ownership and labeling is
22385     * correct for all installed apps. If there is an ownership mismatch, it
22386     * will try recovering system apps by wiping data; third-party app data is
22387     * left intact.
22388     * <p>
22389     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22390     */
22391    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22392        final PackageSetting ps;
22393        synchronized (mPackages) {
22394            ps = mSettings.mPackages.get(pkg.packageName);
22395            mSettings.writeKernelMappingLPr(ps);
22396        }
22397
22398        final UserManager um = mContext.getSystemService(UserManager.class);
22399        UserManagerInternal umInternal = getUserManagerInternal();
22400        for (UserInfo user : um.getUsers()) {
22401            final int flags;
22402            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22403                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22404            } else if (umInternal.isUserRunning(user.id)) {
22405                flags = StorageManager.FLAG_STORAGE_DE;
22406            } else {
22407                continue;
22408            }
22409
22410            if (ps.getInstalled(user.id)) {
22411                // TODO: when user data is locked, mark that we're still dirty
22412                prepareAppDataLIF(pkg, user.id, flags);
22413            }
22414        }
22415    }
22416
22417    /**
22418     * Prepare app data for the given app.
22419     * <p>
22420     * Verifies that directories exist and that ownership and labeling is
22421     * correct for all installed apps. If there is an ownership mismatch, this
22422     * will try recovering system apps by wiping data; third-party app data is
22423     * left intact.
22424     */
22425    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22426        if (pkg == null) {
22427            Slog.wtf(TAG, "Package was null!", new Throwable());
22428            return;
22429        }
22430        prepareAppDataLeafLIF(pkg, userId, flags);
22431        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22432        for (int i = 0; i < childCount; i++) {
22433            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22434        }
22435    }
22436
22437    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22438            boolean maybeMigrateAppData) {
22439        prepareAppDataLIF(pkg, userId, flags);
22440
22441        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22442            // We may have just shuffled around app data directories, so
22443            // prepare them one more time
22444            prepareAppDataLIF(pkg, userId, flags);
22445        }
22446    }
22447
22448    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22449        if (DEBUG_APP_DATA) {
22450            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22451                    + Integer.toHexString(flags));
22452        }
22453
22454        final PackageSetting ps;
22455        synchronized (mPackages) {
22456            ps = mSettings.mPackages.get(pkg.packageName);
22457        }
22458        final String volumeUuid = pkg.volumeUuid;
22459        final String packageName = pkg.packageName;
22460        final ApplicationInfo app = (ps == null)
22461                ? pkg.applicationInfo
22462                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22463
22464        final int appId = UserHandle.getAppId(app.uid);
22465
22466        Preconditions.checkNotNull(app.seInfo);
22467
22468        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22469        long ceDataInode = -1;
22470        try {
22471            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22472                    appId, seInfo, app.targetSdkVersion);
22473        } catch (InstallerException e) {
22474            if (app.isSystemApp()) {
22475                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22476                        + ", but trying to recover: " + e);
22477                destroyAppDataLeafLIF(pkg, userId, flags);
22478                try {
22479                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22480                            appId, seInfo, app.targetSdkVersion);
22481                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22482                } catch (InstallerException e2) {
22483                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22484                }
22485            } else {
22486                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22487            }
22488        }
22489        // Prepare the application profiles only for upgrades and first boot (so that we don't
22490        // repeat the same operation at each boot).
22491        // We only have to cover the upgrade and first boot here because for app installs we
22492        // prepare the profiles before invoking dexopt (in installPackageLI).
22493        //
22494        // We also have to cover non system users because we do not call the usual install package
22495        // methods for them.
22496        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22497            mArtManagerService.prepareAppProfiles(pkg, userId);
22498        }
22499
22500        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22501            // TODO: mark this structure as dirty so we persist it!
22502            synchronized (mPackages) {
22503                if (ps != null) {
22504                    ps.setCeDataInode(ceDataInode, userId);
22505                }
22506            }
22507        }
22508
22509        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22510    }
22511
22512    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22513        if (pkg == null) {
22514            Slog.wtf(TAG, "Package was null!", new Throwable());
22515            return;
22516        }
22517        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22518        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22519        for (int i = 0; i < childCount; i++) {
22520            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22521        }
22522    }
22523
22524    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22525        final String volumeUuid = pkg.volumeUuid;
22526        final String packageName = pkg.packageName;
22527        final ApplicationInfo app = pkg.applicationInfo;
22528
22529        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22530            // Create a native library symlink only if we have native libraries
22531            // and if the native libraries are 32 bit libraries. We do not provide
22532            // this symlink for 64 bit libraries.
22533            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22534                final String nativeLibPath = app.nativeLibraryDir;
22535                try {
22536                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22537                            nativeLibPath, userId);
22538                } catch (InstallerException e) {
22539                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22540                }
22541            }
22542        }
22543    }
22544
22545    /**
22546     * For system apps on non-FBE devices, this method migrates any existing
22547     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22548     * requested by the app.
22549     */
22550    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22551        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22552                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22553            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22554                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22555            try {
22556                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22557                        storageTarget);
22558            } catch (InstallerException e) {
22559                logCriticalInfo(Log.WARN,
22560                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22561            }
22562            return true;
22563        } else {
22564            return false;
22565        }
22566    }
22567
22568    public PackageFreezer freezePackage(String packageName, String killReason) {
22569        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22570    }
22571
22572    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22573        return new PackageFreezer(packageName, userId, killReason);
22574    }
22575
22576    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22577            String killReason) {
22578        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22579    }
22580
22581    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22582            String killReason) {
22583        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22584            return new PackageFreezer();
22585        } else {
22586            return freezePackage(packageName, userId, killReason);
22587        }
22588    }
22589
22590    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22591            String killReason) {
22592        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22593    }
22594
22595    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22596            String killReason) {
22597        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22598            return new PackageFreezer();
22599        } else {
22600            return freezePackage(packageName, userId, killReason);
22601        }
22602    }
22603
22604    /**
22605     * Class that freezes and kills the given package upon creation, and
22606     * unfreezes it upon closing. This is typically used when doing surgery on
22607     * app code/data to prevent the app from running while you're working.
22608     */
22609    private class PackageFreezer implements AutoCloseable {
22610        private final String mPackageName;
22611        private final PackageFreezer[] mChildren;
22612
22613        private final boolean mWeFroze;
22614
22615        private final AtomicBoolean mClosed = new AtomicBoolean();
22616        private final CloseGuard mCloseGuard = CloseGuard.get();
22617
22618        /**
22619         * Create and return a stub freezer that doesn't actually do anything,
22620         * typically used when someone requested
22621         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22622         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22623         */
22624        public PackageFreezer() {
22625            mPackageName = null;
22626            mChildren = null;
22627            mWeFroze = false;
22628            mCloseGuard.open("close");
22629        }
22630
22631        public PackageFreezer(String packageName, int userId, String killReason) {
22632            synchronized (mPackages) {
22633                mPackageName = packageName;
22634                mWeFroze = mFrozenPackages.add(mPackageName);
22635
22636                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22637                if (ps != null) {
22638                    killApplication(ps.name, ps.appId, userId, killReason);
22639                }
22640
22641                final PackageParser.Package p = mPackages.get(packageName);
22642                if (p != null && p.childPackages != null) {
22643                    final int N = p.childPackages.size();
22644                    mChildren = new PackageFreezer[N];
22645                    for (int i = 0; i < N; i++) {
22646                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22647                                userId, killReason);
22648                    }
22649                } else {
22650                    mChildren = null;
22651                }
22652            }
22653            mCloseGuard.open("close");
22654        }
22655
22656        @Override
22657        protected void finalize() throws Throwable {
22658            try {
22659                if (mCloseGuard != null) {
22660                    mCloseGuard.warnIfOpen();
22661                }
22662
22663                close();
22664            } finally {
22665                super.finalize();
22666            }
22667        }
22668
22669        @Override
22670        public void close() {
22671            mCloseGuard.close();
22672            if (mClosed.compareAndSet(false, true)) {
22673                synchronized (mPackages) {
22674                    if (mWeFroze) {
22675                        mFrozenPackages.remove(mPackageName);
22676                    }
22677
22678                    if (mChildren != null) {
22679                        for (PackageFreezer freezer : mChildren) {
22680                            freezer.close();
22681                        }
22682                    }
22683                }
22684            }
22685        }
22686    }
22687
22688    /**
22689     * Verify that given package is currently frozen.
22690     */
22691    private void checkPackageFrozen(String packageName) {
22692        synchronized (mPackages) {
22693            if (!mFrozenPackages.contains(packageName)) {
22694                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22695            }
22696        }
22697    }
22698
22699    @Override
22700    public int movePackage(final String packageName, final String volumeUuid) {
22701        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22702
22703        final int callingUid = Binder.getCallingUid();
22704        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22705        final int moveId = mNextMoveId.getAndIncrement();
22706        mHandler.post(new Runnable() {
22707            @Override
22708            public void run() {
22709                try {
22710                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22711                } catch (PackageManagerException e) {
22712                    Slog.w(TAG, "Failed to move " + packageName, e);
22713                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22714                }
22715            }
22716        });
22717        return moveId;
22718    }
22719
22720    private void movePackageInternal(final String packageName, final String volumeUuid,
22721            final int moveId, final int callingUid, UserHandle user)
22722                    throws PackageManagerException {
22723        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22724        final PackageManager pm = mContext.getPackageManager();
22725
22726        final boolean currentAsec;
22727        final String currentVolumeUuid;
22728        final File codeFile;
22729        final String installerPackageName;
22730        final String packageAbiOverride;
22731        final int appId;
22732        final String seinfo;
22733        final String label;
22734        final int targetSdkVersion;
22735        final PackageFreezer freezer;
22736        final int[] installedUserIds;
22737
22738        // reader
22739        synchronized (mPackages) {
22740            final PackageParser.Package pkg = mPackages.get(packageName);
22741            final PackageSetting ps = mSettings.mPackages.get(packageName);
22742            if (pkg == null
22743                    || ps == null
22744                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22745                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22746            }
22747            if (pkg.applicationInfo.isSystemApp()) {
22748                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22749                        "Cannot move system application");
22750            }
22751
22752            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22753            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22754                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22755            if (isInternalStorage && !allow3rdPartyOnInternal) {
22756                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22757                        "3rd party apps are not allowed on internal storage");
22758            }
22759
22760            if (pkg.applicationInfo.isExternalAsec()) {
22761                currentAsec = true;
22762                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22763            } else if (pkg.applicationInfo.isForwardLocked()) {
22764                currentAsec = true;
22765                currentVolumeUuid = "forward_locked";
22766            } else {
22767                currentAsec = false;
22768                currentVolumeUuid = ps.volumeUuid;
22769
22770                final File probe = new File(pkg.codePath);
22771                final File probeOat = new File(probe, "oat");
22772                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22773                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22774                            "Move only supported for modern cluster style installs");
22775                }
22776            }
22777
22778            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22779                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22780                        "Package already moved to " + volumeUuid);
22781            }
22782            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22783                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22784                        "Device admin cannot be moved");
22785            }
22786
22787            if (mFrozenPackages.contains(packageName)) {
22788                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22789                        "Failed to move already frozen package");
22790            }
22791
22792            codeFile = new File(pkg.codePath);
22793            installerPackageName = ps.installerPackageName;
22794            packageAbiOverride = ps.cpuAbiOverrideString;
22795            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22796            seinfo = pkg.applicationInfo.seInfo;
22797            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22798            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22799            freezer = freezePackage(packageName, "movePackageInternal");
22800            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22801        }
22802
22803        final Bundle extras = new Bundle();
22804        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22805        extras.putString(Intent.EXTRA_TITLE, label);
22806        mMoveCallbacks.notifyCreated(moveId, extras);
22807
22808        int installFlags;
22809        final boolean moveCompleteApp;
22810        final File measurePath;
22811
22812        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22813            installFlags = INSTALL_INTERNAL;
22814            moveCompleteApp = !currentAsec;
22815            measurePath = Environment.getDataAppDirectory(volumeUuid);
22816        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22817            installFlags = INSTALL_EXTERNAL;
22818            moveCompleteApp = false;
22819            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22820        } else {
22821            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22822            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22823                    || !volume.isMountedWritable()) {
22824                freezer.close();
22825                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22826                        "Move location not mounted private volume");
22827            }
22828
22829            Preconditions.checkState(!currentAsec);
22830
22831            installFlags = INSTALL_INTERNAL;
22832            moveCompleteApp = true;
22833            measurePath = Environment.getDataAppDirectory(volumeUuid);
22834        }
22835
22836        // If we're moving app data around, we need all the users unlocked
22837        if (moveCompleteApp) {
22838            for (int userId : installedUserIds) {
22839                if (StorageManager.isFileEncryptedNativeOrEmulated()
22840                        && !StorageManager.isUserKeyUnlocked(userId)) {
22841                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22842                            "User " + userId + " must be unlocked");
22843                }
22844            }
22845        }
22846
22847        final PackageStats stats = new PackageStats(null, -1);
22848        synchronized (mInstaller) {
22849            for (int userId : installedUserIds) {
22850                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22851                    freezer.close();
22852                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22853                            "Failed to measure package size");
22854                }
22855            }
22856        }
22857
22858        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22859                + stats.dataSize);
22860
22861        final long startFreeBytes = measurePath.getUsableSpace();
22862        final long sizeBytes;
22863        if (moveCompleteApp) {
22864            sizeBytes = stats.codeSize + stats.dataSize;
22865        } else {
22866            sizeBytes = stats.codeSize;
22867        }
22868
22869        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22870            freezer.close();
22871            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22872                    "Not enough free space to move");
22873        }
22874
22875        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22876
22877        final CountDownLatch installedLatch = new CountDownLatch(1);
22878        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22879            @Override
22880            public void onUserActionRequired(Intent intent) throws RemoteException {
22881                throw new IllegalStateException();
22882            }
22883
22884            @Override
22885            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22886                    Bundle extras) throws RemoteException {
22887                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22888                        + PackageManager.installStatusToString(returnCode, msg));
22889
22890                installedLatch.countDown();
22891                freezer.close();
22892
22893                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22894                switch (status) {
22895                    case PackageInstaller.STATUS_SUCCESS:
22896                        mMoveCallbacks.notifyStatusChanged(moveId,
22897                                PackageManager.MOVE_SUCCEEDED);
22898                        break;
22899                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22900                        mMoveCallbacks.notifyStatusChanged(moveId,
22901                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22902                        break;
22903                    default:
22904                        mMoveCallbacks.notifyStatusChanged(moveId,
22905                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22906                        break;
22907                }
22908            }
22909        };
22910
22911        final MoveInfo move;
22912        if (moveCompleteApp) {
22913            // Kick off a thread to report progress estimates
22914            new Thread() {
22915                @Override
22916                public void run() {
22917                    while (true) {
22918                        try {
22919                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22920                                break;
22921                            }
22922                        } catch (InterruptedException ignored) {
22923                        }
22924
22925                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22926                        final int progress = 10 + (int) MathUtils.constrain(
22927                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22928                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22929                    }
22930                }
22931            }.start();
22932
22933            final String dataAppName = codeFile.getName();
22934            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22935                    dataAppName, appId, seinfo, targetSdkVersion);
22936        } else {
22937            move = null;
22938        }
22939
22940        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22941
22942        final Message msg = mHandler.obtainMessage(INIT_COPY);
22943        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22944        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22945                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22946                packageAbiOverride, null /*grantedPermissions*/,
22947                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22948        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22949        msg.obj = params;
22950
22951        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22952                System.identityHashCode(msg.obj));
22953        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22954                System.identityHashCode(msg.obj));
22955
22956        mHandler.sendMessage(msg);
22957    }
22958
22959    @Override
22960    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22961        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22962
22963        final int realMoveId = mNextMoveId.getAndIncrement();
22964        final Bundle extras = new Bundle();
22965        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22966        mMoveCallbacks.notifyCreated(realMoveId, extras);
22967
22968        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22969            @Override
22970            public void onCreated(int moveId, Bundle extras) {
22971                // Ignored
22972            }
22973
22974            @Override
22975            public void onStatusChanged(int moveId, int status, long estMillis) {
22976                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22977            }
22978        };
22979
22980        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22981        storage.setPrimaryStorageUuid(volumeUuid, callback);
22982        return realMoveId;
22983    }
22984
22985    @Override
22986    public int getMoveStatus(int moveId) {
22987        mContext.enforceCallingOrSelfPermission(
22988                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22989        return mMoveCallbacks.mLastStatus.get(moveId);
22990    }
22991
22992    @Override
22993    public void registerMoveCallback(IPackageMoveObserver callback) {
22994        mContext.enforceCallingOrSelfPermission(
22995                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22996        mMoveCallbacks.register(callback);
22997    }
22998
22999    @Override
23000    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23001        mContext.enforceCallingOrSelfPermission(
23002                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23003        mMoveCallbacks.unregister(callback);
23004    }
23005
23006    @Override
23007    public boolean setInstallLocation(int loc) {
23008        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23009                null);
23010        if (getInstallLocation() == loc) {
23011            return true;
23012        }
23013        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23014                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23015            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23016                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23017            return true;
23018        }
23019        return false;
23020   }
23021
23022    @Override
23023    public int getInstallLocation() {
23024        // allow instant app access
23025        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23026                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23027                PackageHelper.APP_INSTALL_AUTO);
23028    }
23029
23030    /** Called by UserManagerService */
23031    void cleanUpUser(UserManagerService userManager, int userHandle) {
23032        synchronized (mPackages) {
23033            mDirtyUsers.remove(userHandle);
23034            mUserNeedsBadging.delete(userHandle);
23035            mSettings.removeUserLPw(userHandle);
23036            mPendingBroadcasts.remove(userHandle);
23037            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23038            removeUnusedPackagesLPw(userManager, userHandle);
23039        }
23040    }
23041
23042    /**
23043     * We're removing userHandle and would like to remove any downloaded packages
23044     * that are no longer in use by any other user.
23045     * @param userHandle the user being removed
23046     */
23047    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23048        final boolean DEBUG_CLEAN_APKS = false;
23049        int [] users = userManager.getUserIds();
23050        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23051        while (psit.hasNext()) {
23052            PackageSetting ps = psit.next();
23053            if (ps.pkg == null) {
23054                continue;
23055            }
23056            final String packageName = ps.pkg.packageName;
23057            // Skip over if system app
23058            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23059                continue;
23060            }
23061            if (DEBUG_CLEAN_APKS) {
23062                Slog.i(TAG, "Checking package " + packageName);
23063            }
23064            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23065            if (keep) {
23066                if (DEBUG_CLEAN_APKS) {
23067                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23068                }
23069            } else {
23070                for (int i = 0; i < users.length; i++) {
23071                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23072                        keep = true;
23073                        if (DEBUG_CLEAN_APKS) {
23074                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23075                                    + users[i]);
23076                        }
23077                        break;
23078                    }
23079                }
23080            }
23081            if (!keep) {
23082                if (DEBUG_CLEAN_APKS) {
23083                    Slog.i(TAG, "  Removing package " + packageName);
23084                }
23085                mHandler.post(new Runnable() {
23086                    public void run() {
23087                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23088                                userHandle, 0);
23089                    } //end run
23090                });
23091            }
23092        }
23093    }
23094
23095    /** Called by UserManagerService */
23096    void createNewUser(int userId, String[] disallowedPackages) {
23097        synchronized (mInstallLock) {
23098            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23099        }
23100        synchronized (mPackages) {
23101            scheduleWritePackageRestrictionsLocked(userId);
23102            scheduleWritePackageListLocked(userId);
23103            applyFactoryDefaultBrowserLPw(userId);
23104            primeDomainVerificationsLPw(userId);
23105        }
23106    }
23107
23108    void onNewUserCreated(final int userId) {
23109        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23110        synchronized(mPackages) {
23111            // If permission review for legacy apps is required, we represent
23112            // dagerous permissions for such apps as always granted runtime
23113            // permissions to keep per user flag state whether review is needed.
23114            // Hence, if a new user is added we have to propagate dangerous
23115            // permission grants for these legacy apps.
23116            if (mSettings.mPermissions.mPermissionReviewRequired) {
23117// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23118                mPermissionManager.updateAllPermissions(
23119                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23120                        mPermissionCallback);
23121            }
23122        }
23123    }
23124
23125    @Override
23126    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23127        mContext.enforceCallingOrSelfPermission(
23128                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23129                "Only package verification agents can read the verifier device identity");
23130
23131        synchronized (mPackages) {
23132            return mSettings.getVerifierDeviceIdentityLPw();
23133        }
23134    }
23135
23136    @Override
23137    public void setPermissionEnforced(String permission, boolean enforced) {
23138        // TODO: Now that we no longer change GID for storage, this should to away.
23139        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23140                "setPermissionEnforced");
23141        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23142            synchronized (mPackages) {
23143                if (mSettings.mReadExternalStorageEnforced == null
23144                        || mSettings.mReadExternalStorageEnforced != enforced) {
23145                    mSettings.mReadExternalStorageEnforced =
23146                            enforced ? Boolean.TRUE : Boolean.FALSE;
23147                    mSettings.writeLPr();
23148                }
23149            }
23150            // kill any non-foreground processes so we restart them and
23151            // grant/revoke the GID.
23152            final IActivityManager am = ActivityManager.getService();
23153            if (am != null) {
23154                final long token = Binder.clearCallingIdentity();
23155                try {
23156                    am.killProcessesBelowForeground("setPermissionEnforcement");
23157                } catch (RemoteException e) {
23158                } finally {
23159                    Binder.restoreCallingIdentity(token);
23160                }
23161            }
23162        } else {
23163            throw new IllegalArgumentException("No selective enforcement for " + permission);
23164        }
23165    }
23166
23167    @Override
23168    @Deprecated
23169    public boolean isPermissionEnforced(String permission) {
23170        // allow instant applications
23171        return true;
23172    }
23173
23174    @Override
23175    public boolean isStorageLow() {
23176        // allow instant applications
23177        final long token = Binder.clearCallingIdentity();
23178        try {
23179            final DeviceStorageMonitorInternal
23180                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23181            if (dsm != null) {
23182                return dsm.isMemoryLow();
23183            } else {
23184                return false;
23185            }
23186        } finally {
23187            Binder.restoreCallingIdentity(token);
23188        }
23189    }
23190
23191    @Override
23192    public IPackageInstaller getPackageInstaller() {
23193        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23194            return null;
23195        }
23196        return mInstallerService;
23197    }
23198
23199    @Override
23200    public IArtManager getArtManager() {
23201        return mArtManagerService;
23202    }
23203
23204    private boolean userNeedsBadging(int userId) {
23205        int index = mUserNeedsBadging.indexOfKey(userId);
23206        if (index < 0) {
23207            final UserInfo userInfo;
23208            final long token = Binder.clearCallingIdentity();
23209            try {
23210                userInfo = sUserManager.getUserInfo(userId);
23211            } finally {
23212                Binder.restoreCallingIdentity(token);
23213            }
23214            final boolean b;
23215            if (userInfo != null && userInfo.isManagedProfile()) {
23216                b = true;
23217            } else {
23218                b = false;
23219            }
23220            mUserNeedsBadging.put(userId, b);
23221            return b;
23222        }
23223        return mUserNeedsBadging.valueAt(index);
23224    }
23225
23226    @Override
23227    public KeySet getKeySetByAlias(String packageName, String alias) {
23228        if (packageName == null || alias == null) {
23229            return null;
23230        }
23231        synchronized(mPackages) {
23232            final PackageParser.Package pkg = mPackages.get(packageName);
23233            if (pkg == null) {
23234                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23235                throw new IllegalArgumentException("Unknown package: " + packageName);
23236            }
23237            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23238            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23239                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23240                throw new IllegalArgumentException("Unknown package: " + packageName);
23241            }
23242            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23243            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23244        }
23245    }
23246
23247    @Override
23248    public KeySet getSigningKeySet(String packageName) {
23249        if (packageName == null) {
23250            return null;
23251        }
23252        synchronized(mPackages) {
23253            final int callingUid = Binder.getCallingUid();
23254            final int callingUserId = UserHandle.getUserId(callingUid);
23255            final PackageParser.Package pkg = mPackages.get(packageName);
23256            if (pkg == null) {
23257                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23258                throw new IllegalArgumentException("Unknown package: " + packageName);
23259            }
23260            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23261            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23262                // filter and pretend the package doesn't exist
23263                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23264                        + ", uid:" + callingUid);
23265                throw new IllegalArgumentException("Unknown package: " + packageName);
23266            }
23267            if (pkg.applicationInfo.uid != callingUid
23268                    && Process.SYSTEM_UID != callingUid) {
23269                throw new SecurityException("May not access signing KeySet of other apps.");
23270            }
23271            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23272            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23273        }
23274    }
23275
23276    @Override
23277    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23278        final int callingUid = Binder.getCallingUid();
23279        if (getInstantAppPackageName(callingUid) != null) {
23280            return false;
23281        }
23282        if (packageName == null || ks == null) {
23283            return false;
23284        }
23285        synchronized(mPackages) {
23286            final PackageParser.Package pkg = mPackages.get(packageName);
23287            if (pkg == null
23288                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23289                            UserHandle.getUserId(callingUid))) {
23290                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23291                throw new IllegalArgumentException("Unknown package: " + packageName);
23292            }
23293            IBinder ksh = ks.getToken();
23294            if (ksh instanceof KeySetHandle) {
23295                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23296                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23297            }
23298            return false;
23299        }
23300    }
23301
23302    @Override
23303    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23304        final int callingUid = Binder.getCallingUid();
23305        if (getInstantAppPackageName(callingUid) != null) {
23306            return false;
23307        }
23308        if (packageName == null || ks == null) {
23309            return false;
23310        }
23311        synchronized(mPackages) {
23312            final PackageParser.Package pkg = mPackages.get(packageName);
23313            if (pkg == null
23314                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23315                            UserHandle.getUserId(callingUid))) {
23316                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23317                throw new IllegalArgumentException("Unknown package: " + packageName);
23318            }
23319            IBinder ksh = ks.getToken();
23320            if (ksh instanceof KeySetHandle) {
23321                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23322                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23323            }
23324            return false;
23325        }
23326    }
23327
23328    private void deletePackageIfUnusedLPr(final String packageName) {
23329        PackageSetting ps = mSettings.mPackages.get(packageName);
23330        if (ps == null) {
23331            return;
23332        }
23333        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23334            // TODO Implement atomic delete if package is unused
23335            // It is currently possible that the package will be deleted even if it is installed
23336            // after this method returns.
23337            mHandler.post(new Runnable() {
23338                public void run() {
23339                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23340                            0, PackageManager.DELETE_ALL_USERS);
23341                }
23342            });
23343        }
23344    }
23345
23346    /**
23347     * Check and throw if the given before/after packages would be considered a
23348     * downgrade.
23349     */
23350    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23351            throws PackageManagerException {
23352        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23353            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23354                    "Update version code " + after.versionCode + " is older than current "
23355                    + before.getLongVersionCode());
23356        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23357            if (after.baseRevisionCode < before.baseRevisionCode) {
23358                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23359                        "Update base revision code " + after.baseRevisionCode
23360                        + " is older than current " + before.baseRevisionCode);
23361            }
23362
23363            if (!ArrayUtils.isEmpty(after.splitNames)) {
23364                for (int i = 0; i < after.splitNames.length; i++) {
23365                    final String splitName = after.splitNames[i];
23366                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23367                    if (j != -1) {
23368                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23369                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23370                                    "Update split " + splitName + " revision code "
23371                                    + after.splitRevisionCodes[i] + " is older than current "
23372                                    + before.splitRevisionCodes[j]);
23373                        }
23374                    }
23375                }
23376            }
23377        }
23378    }
23379
23380    private static class MoveCallbacks extends Handler {
23381        private static final int MSG_CREATED = 1;
23382        private static final int MSG_STATUS_CHANGED = 2;
23383
23384        private final RemoteCallbackList<IPackageMoveObserver>
23385                mCallbacks = new RemoteCallbackList<>();
23386
23387        private final SparseIntArray mLastStatus = new SparseIntArray();
23388
23389        public MoveCallbacks(Looper looper) {
23390            super(looper);
23391        }
23392
23393        public void register(IPackageMoveObserver callback) {
23394            mCallbacks.register(callback);
23395        }
23396
23397        public void unregister(IPackageMoveObserver callback) {
23398            mCallbacks.unregister(callback);
23399        }
23400
23401        @Override
23402        public void handleMessage(Message msg) {
23403            final SomeArgs args = (SomeArgs) msg.obj;
23404            final int n = mCallbacks.beginBroadcast();
23405            for (int i = 0; i < n; i++) {
23406                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23407                try {
23408                    invokeCallback(callback, msg.what, args);
23409                } catch (RemoteException ignored) {
23410                }
23411            }
23412            mCallbacks.finishBroadcast();
23413            args.recycle();
23414        }
23415
23416        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23417                throws RemoteException {
23418            switch (what) {
23419                case MSG_CREATED: {
23420                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23421                    break;
23422                }
23423                case MSG_STATUS_CHANGED: {
23424                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23425                    break;
23426                }
23427            }
23428        }
23429
23430        private void notifyCreated(int moveId, Bundle extras) {
23431            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23432
23433            final SomeArgs args = SomeArgs.obtain();
23434            args.argi1 = moveId;
23435            args.arg2 = extras;
23436            obtainMessage(MSG_CREATED, args).sendToTarget();
23437        }
23438
23439        private void notifyStatusChanged(int moveId, int status) {
23440            notifyStatusChanged(moveId, status, -1);
23441        }
23442
23443        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23444            Slog.v(TAG, "Move " + moveId + " status " + status);
23445
23446            final SomeArgs args = SomeArgs.obtain();
23447            args.argi1 = moveId;
23448            args.argi2 = status;
23449            args.arg3 = estMillis;
23450            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23451
23452            synchronized (mLastStatus) {
23453                mLastStatus.put(moveId, status);
23454            }
23455        }
23456    }
23457
23458    private final static class OnPermissionChangeListeners extends Handler {
23459        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23460
23461        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23462                new RemoteCallbackList<>();
23463
23464        public OnPermissionChangeListeners(Looper looper) {
23465            super(looper);
23466        }
23467
23468        @Override
23469        public void handleMessage(Message msg) {
23470            switch (msg.what) {
23471                case MSG_ON_PERMISSIONS_CHANGED: {
23472                    final int uid = msg.arg1;
23473                    handleOnPermissionsChanged(uid);
23474                } break;
23475            }
23476        }
23477
23478        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23479            mPermissionListeners.register(listener);
23480
23481        }
23482
23483        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23484            mPermissionListeners.unregister(listener);
23485        }
23486
23487        public void onPermissionsChanged(int uid) {
23488            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23489                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23490            }
23491        }
23492
23493        private void handleOnPermissionsChanged(int uid) {
23494            final int count = mPermissionListeners.beginBroadcast();
23495            try {
23496                for (int i = 0; i < count; i++) {
23497                    IOnPermissionsChangeListener callback = mPermissionListeners
23498                            .getBroadcastItem(i);
23499                    try {
23500                        callback.onPermissionsChanged(uid);
23501                    } catch (RemoteException e) {
23502                        Log.e(TAG, "Permission listener is dead", e);
23503                    }
23504                }
23505            } finally {
23506                mPermissionListeners.finishBroadcast();
23507            }
23508        }
23509    }
23510
23511    private class PackageManagerNative extends IPackageManagerNative.Stub {
23512        @Override
23513        public String[] getNamesForUids(int[] uids) throws RemoteException {
23514            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23515            // massage results so they can be parsed by the native binder
23516            for (int i = results.length - 1; i >= 0; --i) {
23517                if (results[i] == null) {
23518                    results[i] = "";
23519                }
23520            }
23521            return results;
23522        }
23523
23524        // NB: this differentiates between preloads and sideloads
23525        @Override
23526        public String getInstallerForPackage(String packageName) throws RemoteException {
23527            final String installerName = getInstallerPackageName(packageName);
23528            if (!TextUtils.isEmpty(installerName)) {
23529                return installerName;
23530            }
23531            // differentiate between preload and sideload
23532            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23533            ApplicationInfo appInfo = getApplicationInfo(packageName,
23534                                    /*flags*/ 0,
23535                                    /*userId*/ callingUser);
23536            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23537                return "preload";
23538            }
23539            return "";
23540        }
23541
23542        @Override
23543        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23544            try {
23545                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23546                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23547                if (pInfo != null) {
23548                    return pInfo.getLongVersionCode();
23549                }
23550            } catch (Exception e) {
23551            }
23552            return 0;
23553        }
23554    }
23555
23556    private class PackageManagerInternalImpl extends PackageManagerInternal {
23557        @Override
23558        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23559                int flagValues, int userId) {
23560            PackageManagerService.this.updatePermissionFlags(
23561                    permName, packageName, flagMask, flagValues, userId);
23562        }
23563
23564        @Override
23565        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23566            SigningDetails sd = getSigningDetails(packageName);
23567            if (sd == null) {
23568                return false;
23569            }
23570            return sd.hasSha256Certificate(restoringFromSigHash,
23571                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23572        }
23573
23574        @Override
23575        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23576            SigningDetails sd = getSigningDetails(packageName);
23577            if (sd == null) {
23578                return false;
23579            }
23580            return sd.hasCertificate(restoringFromSig,
23581                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23582        }
23583
23584        private SigningDetails getSigningDetails(@NonNull String packageName) {
23585            synchronized (mPackages) {
23586                PackageParser.Package p = mPackages.get(packageName);
23587                if (p == null) {
23588                    return null;
23589                }
23590                return p.mSigningDetails;
23591            }
23592        }
23593
23594        @Override
23595        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23596            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23597        }
23598
23599        @Override
23600        public boolean isInstantApp(String packageName, int userId) {
23601            return PackageManagerService.this.isInstantApp(packageName, userId);
23602        }
23603
23604        @Override
23605        public String getInstantAppPackageName(int uid) {
23606            return PackageManagerService.this.getInstantAppPackageName(uid);
23607        }
23608
23609        @Override
23610        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23611            synchronized (mPackages) {
23612                return PackageManagerService.this.filterAppAccessLPr(
23613                        (PackageSetting) pkg.mExtras, callingUid, userId);
23614            }
23615        }
23616
23617        @Override
23618        public PackageParser.Package getPackage(String packageName) {
23619            synchronized (mPackages) {
23620                packageName = resolveInternalPackageNameLPr(
23621                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23622                return mPackages.get(packageName);
23623            }
23624        }
23625
23626        @Override
23627        public Object getPackageSetting(String packageName) {
23628            synchronized (mPackages) {
23629                return mSettings.getPackageLPr(packageName);
23630            }
23631        }
23632
23633        @Override
23634        public PackageList getPackageList(PackageListObserver observer) {
23635            synchronized (mPackages) {
23636                final int N = mPackages.size();
23637                final ArrayList<String> list = new ArrayList<>(N);
23638                for (int i = 0; i < N; i++) {
23639                    list.add(mPackages.keyAt(i));
23640                }
23641                final PackageList packageList = new PackageList(list, observer);
23642                if (observer != null) {
23643                    mPackageListObservers.add(packageList);
23644                }
23645                return packageList;
23646            }
23647        }
23648
23649        @Override
23650        public void removePackageListObserver(PackageListObserver observer) {
23651            synchronized (mPackages) {
23652                mPackageListObservers.remove(observer);
23653            }
23654        }
23655
23656        @Override
23657        public PackageParser.Package getDisabledPackage(String packageName) {
23658            synchronized (mPackages) {
23659                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23660                return (ps != null) ? ps.pkg : null;
23661            }
23662        }
23663
23664        @Override
23665        public String getKnownPackageName(int knownPackage, int userId) {
23666            switch(knownPackage) {
23667                case PackageManagerInternal.PACKAGE_BROWSER:
23668                    return getDefaultBrowserPackageName(userId);
23669                case PackageManagerInternal.PACKAGE_INSTALLER:
23670                    return mRequiredInstallerPackage;
23671                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23672                    return mSetupWizardPackage;
23673                case PackageManagerInternal.PACKAGE_SYSTEM:
23674                    return "android";
23675                case PackageManagerInternal.PACKAGE_VERIFIER:
23676                    return mRequiredVerifierPackage;
23677                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23678                    return mSystemTextClassifierPackage;
23679            }
23680            return null;
23681        }
23682
23683        @Override
23684        public boolean isResolveActivityComponent(ComponentInfo component) {
23685            return mResolveActivity.packageName.equals(component.packageName)
23686                    && mResolveActivity.name.equals(component.name);
23687        }
23688
23689        @Override
23690        public void setLocationPackagesProvider(PackagesProvider provider) {
23691            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23692        }
23693
23694        @Override
23695        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23696            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23697        }
23698
23699        @Override
23700        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23701            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23702        }
23703
23704        @Override
23705        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23706            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23707        }
23708
23709        @Override
23710        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23711            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23712        }
23713
23714        @Override
23715        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23716            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23717        }
23718
23719        @Override
23720        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23721            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23722        }
23723
23724        @Override
23725        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23726            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23727        }
23728
23729        @Override
23730        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23731            synchronized (mPackages) {
23732                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23733            }
23734            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23735        }
23736
23737        @Override
23738        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23739            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23740                    packageName, userId);
23741        }
23742
23743        @Override
23744        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23745            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23746                    packageName, userId);
23747        }
23748
23749        @Override
23750        public void setKeepUninstalledPackages(final List<String> packageList) {
23751            Preconditions.checkNotNull(packageList);
23752            List<String> removedFromList = null;
23753            synchronized (mPackages) {
23754                if (mKeepUninstalledPackages != null) {
23755                    final int packagesCount = mKeepUninstalledPackages.size();
23756                    for (int i = 0; i < packagesCount; i++) {
23757                        String oldPackage = mKeepUninstalledPackages.get(i);
23758                        if (packageList != null && packageList.contains(oldPackage)) {
23759                            continue;
23760                        }
23761                        if (removedFromList == null) {
23762                            removedFromList = new ArrayList<>();
23763                        }
23764                        removedFromList.add(oldPackage);
23765                    }
23766                }
23767                mKeepUninstalledPackages = new ArrayList<>(packageList);
23768                if (removedFromList != null) {
23769                    final int removedCount = removedFromList.size();
23770                    for (int i = 0; i < removedCount; i++) {
23771                        deletePackageIfUnusedLPr(removedFromList.get(i));
23772                    }
23773                }
23774            }
23775        }
23776
23777        @Override
23778        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23779            synchronized (mPackages) {
23780                return mPermissionManager.isPermissionsReviewRequired(
23781                        mPackages.get(packageName), userId);
23782            }
23783        }
23784
23785        @Override
23786        public PackageInfo getPackageInfo(
23787                String packageName, int flags, int filterCallingUid, int userId) {
23788            return PackageManagerService.this
23789                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23790                            flags, filterCallingUid, userId);
23791        }
23792
23793        @Override
23794        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23795            synchronized (mPackages) {
23796                final PackageSetting ps = mSettings.mPackages.get(packageName);
23797                PersistableBundle launcherExtras = null;
23798                if (ps != null) {
23799                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23800                }
23801                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23802            }
23803        }
23804
23805        @Override
23806        public boolean isPackageSuspended(String packageName, int userId) {
23807            synchronized (mPackages) {
23808                final PackageSetting ps = mSettings.mPackages.get(packageName);
23809                return (ps != null) ? ps.getSuspended(userId) : false;
23810            }
23811        }
23812
23813        @Override
23814        public String getSuspendingPackage(String suspendedPackage, int userId) {
23815            synchronized (mPackages) {
23816                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23817                return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
23818            }
23819        }
23820
23821        @Override
23822        public String getSuspendedDialogMessage(String suspendedPackage, int userId) {
23823            synchronized (mPackages) {
23824                final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
23825                return (ps != null) ? ps.readUserState(userId).dialogMessage : null;
23826            }
23827        }
23828
23829        @Override
23830        public int getPackageUid(String packageName, int flags, int userId) {
23831            return PackageManagerService.this
23832                    .getPackageUid(packageName, flags, userId);
23833        }
23834
23835        @Override
23836        public ApplicationInfo getApplicationInfo(
23837                String packageName, int flags, int filterCallingUid, int userId) {
23838            return PackageManagerService.this
23839                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23840        }
23841
23842        @Override
23843        public ActivityInfo getActivityInfo(
23844                ComponentName component, int flags, int filterCallingUid, int userId) {
23845            return PackageManagerService.this
23846                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23847        }
23848
23849        @Override
23850        public List<ResolveInfo> queryIntentActivities(
23851                Intent intent, int flags, int filterCallingUid, int userId) {
23852            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23853            return PackageManagerService.this
23854                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23855                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23856        }
23857
23858        @Override
23859        public List<ResolveInfo> queryIntentServices(
23860                Intent intent, int flags, int callingUid, int userId) {
23861            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23862            return PackageManagerService.this
23863                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23864                            false);
23865        }
23866
23867        @Override
23868        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23869                int userId) {
23870            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23871        }
23872
23873        @Override
23874        public ComponentName getDefaultHomeActivity(int userId) {
23875            return PackageManagerService.this.getDefaultHomeActivity(userId);
23876        }
23877
23878        @Override
23879        public void setDeviceAndProfileOwnerPackages(
23880                int deviceOwnerUserId, String deviceOwnerPackage,
23881                SparseArray<String> profileOwnerPackages) {
23882            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23883                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23884        }
23885
23886        @Override
23887        public boolean isPackageDataProtected(int userId, String packageName) {
23888            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23889        }
23890
23891        @Override
23892        public boolean isPackageEphemeral(int userId, String packageName) {
23893            synchronized (mPackages) {
23894                final PackageSetting ps = mSettings.mPackages.get(packageName);
23895                return ps != null ? ps.getInstantApp(userId) : false;
23896            }
23897        }
23898
23899        @Override
23900        public boolean wasPackageEverLaunched(String packageName, int userId) {
23901            synchronized (mPackages) {
23902                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23903            }
23904        }
23905
23906        @Override
23907        public void grantRuntimePermission(String packageName, String permName, int userId,
23908                boolean overridePolicy) {
23909            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23910                    permName, packageName, overridePolicy, getCallingUid(), userId,
23911                    mPermissionCallback);
23912        }
23913
23914        @Override
23915        public void revokeRuntimePermission(String packageName, String permName, int userId,
23916                boolean overridePolicy) {
23917            mPermissionManager.revokeRuntimePermission(
23918                    permName, packageName, overridePolicy, getCallingUid(), userId,
23919                    mPermissionCallback);
23920        }
23921
23922        @Override
23923        public String getNameForUid(int uid) {
23924            return PackageManagerService.this.getNameForUid(uid);
23925        }
23926
23927        @Override
23928        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23929                Intent origIntent, String resolvedType, String callingPackage,
23930                Bundle verificationBundle, int userId) {
23931            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23932                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23933                    userId);
23934        }
23935
23936        @Override
23937        public void grantEphemeralAccess(int userId, Intent intent,
23938                int targetAppId, int ephemeralAppId) {
23939            synchronized (mPackages) {
23940                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23941                        targetAppId, ephemeralAppId);
23942            }
23943        }
23944
23945        @Override
23946        public boolean isInstantAppInstallerComponent(ComponentName component) {
23947            synchronized (mPackages) {
23948                return mInstantAppInstallerActivity != null
23949                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23950            }
23951        }
23952
23953        @Override
23954        public void pruneInstantApps() {
23955            mInstantAppRegistry.pruneInstantApps();
23956        }
23957
23958        @Override
23959        public String getSetupWizardPackageName() {
23960            return mSetupWizardPackage;
23961        }
23962
23963        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23964            if (policy != null) {
23965                mExternalSourcesPolicy = policy;
23966            }
23967        }
23968
23969        @Override
23970        public boolean isPackagePersistent(String packageName) {
23971            synchronized (mPackages) {
23972                PackageParser.Package pkg = mPackages.get(packageName);
23973                return pkg != null
23974                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23975                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23976                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23977                        : false;
23978            }
23979        }
23980
23981        @Override
23982        public boolean isLegacySystemApp(Package pkg) {
23983            synchronized (mPackages) {
23984                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23985                return mPromoteSystemApps
23986                        && ps.isSystem()
23987                        && mExistingSystemPackages.contains(ps.name);
23988            }
23989        }
23990
23991        @Override
23992        public List<PackageInfo> getOverlayPackages(int userId) {
23993            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23994            synchronized (mPackages) {
23995                for (PackageParser.Package p : mPackages.values()) {
23996                    if (p.mOverlayTarget != null) {
23997                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23998                        if (pkg != null) {
23999                            overlayPackages.add(pkg);
24000                        }
24001                    }
24002                }
24003            }
24004            return overlayPackages;
24005        }
24006
24007        @Override
24008        public List<String> getTargetPackageNames(int userId) {
24009            List<String> targetPackages = new ArrayList<>();
24010            synchronized (mPackages) {
24011                for (PackageParser.Package p : mPackages.values()) {
24012                    if (p.mOverlayTarget == null) {
24013                        targetPackages.add(p.packageName);
24014                    }
24015                }
24016            }
24017            return targetPackages;
24018        }
24019
24020        @Override
24021        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24022                @Nullable List<String> overlayPackageNames) {
24023            synchronized (mPackages) {
24024                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24025                    Slog.e(TAG, "failed to find package " + targetPackageName);
24026                    return false;
24027                }
24028                ArrayList<String> overlayPaths = null;
24029                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24030                    final int N = overlayPackageNames.size();
24031                    overlayPaths = new ArrayList<>(N);
24032                    for (int i = 0; i < N; i++) {
24033                        final String packageName = overlayPackageNames.get(i);
24034                        final PackageParser.Package pkg = mPackages.get(packageName);
24035                        if (pkg == null) {
24036                            Slog.e(TAG, "failed to find package " + packageName);
24037                            return false;
24038                        }
24039                        overlayPaths.add(pkg.baseCodePath);
24040                    }
24041                }
24042
24043                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24044                ps.setOverlayPaths(overlayPaths, userId);
24045                return true;
24046            }
24047        }
24048
24049        @Override
24050        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24051                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24052            return resolveIntentInternal(
24053                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24054        }
24055
24056        @Override
24057        public ResolveInfo resolveService(Intent intent, String resolvedType,
24058                int flags, int userId, int callingUid) {
24059            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24060        }
24061
24062        @Override
24063        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24064            return PackageManagerService.this.resolveContentProviderInternal(
24065                    name, flags, userId);
24066        }
24067
24068        @Override
24069        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24070            synchronized (mPackages) {
24071                mIsolatedOwners.put(isolatedUid, ownerUid);
24072            }
24073        }
24074
24075        @Override
24076        public void removeIsolatedUid(int isolatedUid) {
24077            synchronized (mPackages) {
24078                mIsolatedOwners.delete(isolatedUid);
24079            }
24080        }
24081
24082        @Override
24083        public int getUidTargetSdkVersion(int uid) {
24084            synchronized (mPackages) {
24085                return getUidTargetSdkVersionLockedLPr(uid);
24086            }
24087        }
24088
24089        @Override
24090        public int getPackageTargetSdkVersion(String packageName) {
24091            synchronized (mPackages) {
24092                return getPackageTargetSdkVersionLockedLPr(packageName);
24093            }
24094        }
24095
24096        @Override
24097        public boolean canAccessInstantApps(int callingUid, int userId) {
24098            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24099        }
24100
24101        @Override
24102        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24103            synchronized (mPackages) {
24104                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24105                return !PackageManagerService.this.filterAppAccessLPr(
24106                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24107            }
24108        }
24109
24110        @Override
24111        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24112            synchronized (mPackages) {
24113                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24114            }
24115        }
24116
24117        @Override
24118        public void notifyPackageUse(String packageName, int reason) {
24119            synchronized (mPackages) {
24120                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24121            }
24122        }
24123    }
24124
24125    @Override
24126    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24127        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24128        synchronized (mPackages) {
24129            final long identity = Binder.clearCallingIdentity();
24130            try {
24131                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24132                        packageNames, userId);
24133            } finally {
24134                Binder.restoreCallingIdentity(identity);
24135            }
24136        }
24137    }
24138
24139    @Override
24140    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24141        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24142        synchronized (mPackages) {
24143            final long identity = Binder.clearCallingIdentity();
24144            try {
24145                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24146                        packageNames, userId);
24147            } finally {
24148                Binder.restoreCallingIdentity(identity);
24149            }
24150        }
24151    }
24152
24153    @Override
24154    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24155            String[] packageNames, int userId) {
24156        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24157        synchronized (mPackages) {
24158            Binder.withCleanCallingIdentity( () -> {
24159                mDefaultPermissionPolicy.
24160                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24161                                packageNames, userId);
24162            });
24163        }
24164    }
24165
24166    @Override
24167    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24168            String[] packageNames, int userId) {
24169        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24170        synchronized (mPackages) {
24171            Binder.withCleanCallingIdentity( () -> {
24172                mDefaultPermissionPolicy.
24173                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24174                                packageNames, userId);
24175            });
24176        }
24177    }
24178
24179    @Override
24180    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24181        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24182        synchronized (mPackages) {
24183            final long identity = Binder.clearCallingIdentity();
24184            try {
24185                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24186                        packageName, userId);
24187            } finally {
24188                Binder.restoreCallingIdentity(identity);
24189            }
24190        }
24191    }
24192
24193    @Override
24194    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24195        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24196        synchronized (mPackages) {
24197            final long identity = Binder.clearCallingIdentity();
24198            try {
24199                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24200            } finally {
24201                Binder.restoreCallingIdentity(identity);
24202            }
24203        }
24204    }
24205
24206    private static void enforceSystemOrPhoneCaller(String tag) {
24207        int callingUid = Binder.getCallingUid();
24208        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24209            throw new SecurityException(
24210                    "Cannot call " + tag + " from UID " + callingUid);
24211        }
24212    }
24213
24214    boolean isHistoricalPackageUsageAvailable() {
24215        return mPackageUsage.isHistoricalPackageUsageAvailable();
24216    }
24217
24218    /**
24219     * Return a <b>copy</b> of the collection of packages known to the package manager.
24220     * @return A copy of the values of mPackages.
24221     */
24222    Collection<PackageParser.Package> getPackages() {
24223        synchronized (mPackages) {
24224            return new ArrayList<>(mPackages.values());
24225        }
24226    }
24227
24228    /**
24229     * Logs process start information (including base APK hash) to the security log.
24230     * @hide
24231     */
24232    @Override
24233    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24234            String apkFile, int pid) {
24235        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24236            return;
24237        }
24238        if (!SecurityLog.isLoggingEnabled()) {
24239            return;
24240        }
24241        Bundle data = new Bundle();
24242        data.putLong("startTimestamp", System.currentTimeMillis());
24243        data.putString("processName", processName);
24244        data.putInt("uid", uid);
24245        data.putString("seinfo", seinfo);
24246        data.putString("apkFile", apkFile);
24247        data.putInt("pid", pid);
24248        Message msg = mProcessLoggingHandler.obtainMessage(
24249                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24250        msg.setData(data);
24251        mProcessLoggingHandler.sendMessage(msg);
24252    }
24253
24254    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24255        return mCompilerStats.getPackageStats(pkgName);
24256    }
24257
24258    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24259        return getOrCreateCompilerPackageStats(pkg.packageName);
24260    }
24261
24262    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24263        return mCompilerStats.getOrCreatePackageStats(pkgName);
24264    }
24265
24266    public void deleteCompilerPackageStats(String pkgName) {
24267        mCompilerStats.deletePackageStats(pkgName);
24268    }
24269
24270    @Override
24271    public int getInstallReason(String packageName, int userId) {
24272        final int callingUid = Binder.getCallingUid();
24273        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24274                true /* requireFullPermission */, false /* checkShell */,
24275                "get install reason");
24276        synchronized (mPackages) {
24277            final PackageSetting ps = mSettings.mPackages.get(packageName);
24278            if (filterAppAccessLPr(ps, callingUid, userId)) {
24279                return PackageManager.INSTALL_REASON_UNKNOWN;
24280            }
24281            if (ps != null) {
24282                return ps.getInstallReason(userId);
24283            }
24284        }
24285        return PackageManager.INSTALL_REASON_UNKNOWN;
24286    }
24287
24288    @Override
24289    public boolean canRequestPackageInstalls(String packageName, int userId) {
24290        return canRequestPackageInstallsInternal(packageName, 0, userId,
24291                true /* throwIfPermNotDeclared*/);
24292    }
24293
24294    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24295            boolean throwIfPermNotDeclared) {
24296        int callingUid = Binder.getCallingUid();
24297        int uid = getPackageUid(packageName, 0, userId);
24298        if (callingUid != uid && callingUid != Process.ROOT_UID
24299                && callingUid != Process.SYSTEM_UID) {
24300            throw new SecurityException(
24301                    "Caller uid " + callingUid + " does not own package " + packageName);
24302        }
24303        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24304        if (info == null) {
24305            return false;
24306        }
24307        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24308            return false;
24309        }
24310        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24311        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24312        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24313            if (throwIfPermNotDeclared) {
24314                throw new SecurityException("Need to declare " + appOpPermission
24315                        + " to call this api");
24316            } else {
24317                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24318                return false;
24319            }
24320        }
24321        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24322            return false;
24323        }
24324        if (mExternalSourcesPolicy != null) {
24325            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24326            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24327                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24328            }
24329        }
24330        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24331    }
24332
24333    @Override
24334    public ComponentName getInstantAppResolverSettingsComponent() {
24335        return mInstantAppResolverSettingsComponent;
24336    }
24337
24338    @Override
24339    public ComponentName getInstantAppInstallerComponent() {
24340        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24341            return null;
24342        }
24343        return mInstantAppInstallerActivity == null
24344                ? null : mInstantAppInstallerActivity.getComponentName();
24345    }
24346
24347    @Override
24348    public String getInstantAppAndroidId(String packageName, int userId) {
24349        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24350                "getInstantAppAndroidId");
24351        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24352                true /* requireFullPermission */, false /* checkShell */,
24353                "getInstantAppAndroidId");
24354        // Make sure the target is an Instant App.
24355        if (!isInstantApp(packageName, userId)) {
24356            return null;
24357        }
24358        synchronized (mPackages) {
24359            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24360        }
24361    }
24362
24363    boolean canHaveOatDir(String packageName) {
24364        synchronized (mPackages) {
24365            PackageParser.Package p = mPackages.get(packageName);
24366            if (p == null) {
24367                return false;
24368            }
24369            return p.canHaveOatDir();
24370        }
24371    }
24372
24373    private String getOatDir(PackageParser.Package pkg) {
24374        if (!pkg.canHaveOatDir()) {
24375            return null;
24376        }
24377        File codePath = new File(pkg.codePath);
24378        if (codePath.isDirectory()) {
24379            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24380        }
24381        return null;
24382    }
24383
24384    void deleteOatArtifactsOfPackage(String packageName) {
24385        final String[] instructionSets;
24386        final List<String> codePaths;
24387        final String oatDir;
24388        final PackageParser.Package pkg;
24389        synchronized (mPackages) {
24390            pkg = mPackages.get(packageName);
24391        }
24392        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24393        codePaths = pkg.getAllCodePaths();
24394        oatDir = getOatDir(pkg);
24395
24396        for (String codePath : codePaths) {
24397            for (String isa : instructionSets) {
24398                try {
24399                    mInstaller.deleteOdex(codePath, isa, oatDir);
24400                } catch (InstallerException e) {
24401                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24402                }
24403            }
24404        }
24405    }
24406
24407    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24408        Set<String> unusedPackages = new HashSet<>();
24409        long currentTimeInMillis = System.currentTimeMillis();
24410        synchronized (mPackages) {
24411            for (PackageParser.Package pkg : mPackages.values()) {
24412                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24413                if (ps == null) {
24414                    continue;
24415                }
24416                PackageDexUsage.PackageUseInfo packageUseInfo =
24417                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24418                if (PackageManagerServiceUtils
24419                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24420                                downgradeTimeThresholdMillis, packageUseInfo,
24421                                pkg.getLatestPackageUseTimeInMills(),
24422                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24423                    unusedPackages.add(pkg.packageName);
24424                }
24425            }
24426        }
24427        return unusedPackages;
24428    }
24429
24430    @Override
24431    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24432            int userId) {
24433        final int callingUid = Binder.getCallingUid();
24434        final int callingAppId = UserHandle.getAppId(callingUid);
24435
24436        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24437                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24438
24439        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24440                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24441            throw new SecurityException("Caller must have the "
24442                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24443        }
24444
24445        synchronized(mPackages) {
24446            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24447            scheduleWritePackageRestrictionsLocked(userId);
24448        }
24449    }
24450
24451    @Nullable
24452    @Override
24453    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24454        final int callingUid = Binder.getCallingUid();
24455        final int callingAppId = UserHandle.getAppId(callingUid);
24456
24457        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24458                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24459
24460        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24461                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24462            throw new SecurityException("Caller must have the "
24463                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24464        }
24465
24466        synchronized(mPackages) {
24467            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24468        }
24469    }
24470
24471    @Override
24472    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24473        final int callingUid = Binder.getCallingUid();
24474        final int callingAppId = UserHandle.getAppId(callingUid);
24475
24476        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24477                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24478
24479        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24480                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24481            throw new SecurityException("Caller must have the "
24482                    + MANAGE_DEVICE_ADMINS + " permission.");
24483        }
24484
24485        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24486    }
24487}
24488
24489interface PackageSender {
24490    /**
24491     * @param userIds User IDs where the action occurred on a full application
24492     * @param instantUserIds User IDs where the action occurred on an instant application
24493     */
24494    void sendPackageBroadcast(final String action, final String pkg,
24495        final Bundle extras, final int flags, final String targetPkg,
24496        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24497    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24498        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24499    void notifyPackageAdded(String packageName);
24500    void notifyPackageRemoved(String packageName);
24501}
24502