PackageManagerService.java revision c4a6070d2442fbe227af6e9d6005b5922d7669c0
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.content.NativeLibraryHelper;
278import com.android.internal.content.PackageHelper;
279import com.android.internal.logging.MetricsLogger;
280import com.android.internal.os.IParcelFileDescriptorFactory;
281import com.android.internal.os.SomeArgs;
282import com.android.internal.os.Zygote;
283import com.android.internal.telephony.CarrierAppUtils;
284import com.android.internal.util.ArrayUtils;
285import com.android.internal.util.ConcurrentUtils;
286import com.android.internal.util.DumpUtils;
287import com.android.internal.util.FastXmlSerializer;
288import com.android.internal.util.IndentingPrintWriter;
289import com.android.internal.util.Preconditions;
290import com.android.internal.util.XmlUtils;
291import com.android.server.AttributeCache;
292import com.android.server.DeviceIdleController;
293import com.android.server.EventLogTags;
294import com.android.server.FgThread;
295import com.android.server.IntentResolver;
296import com.android.server.LocalServices;
297import com.android.server.LockGuard;
298import com.android.server.ServiceThread;
299import com.android.server.SystemConfig;
300import com.android.server.SystemServerInitThreadPool;
301import com.android.server.Watchdog;
302import com.android.server.net.NetworkPolicyManagerInternal;
303import com.android.server.pm.Installer.InstallerException;
304import com.android.server.pm.Settings.DatabaseVersion;
305import com.android.server.pm.Settings.VersionInfo;
306import com.android.server.pm.dex.ArtManagerService;
307import com.android.server.pm.dex.DexLogger;
308import com.android.server.pm.dex.DexManager;
309import com.android.server.pm.dex.DexoptOptions;
310import com.android.server.pm.dex.PackageDexUsage;
311import com.android.server.pm.permission.BasePermission;
312import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
313import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
314import com.android.server.pm.permission.PermissionManagerInternal;
315import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
316import com.android.server.pm.permission.PermissionManagerService;
317import com.android.server.pm.permission.PermissionsState;
318import com.android.server.pm.permission.PermissionsState.PermissionState;
319import com.android.server.security.VerityUtils;
320import com.android.server.storage.DeviceStorageMonitorInternal;
321
322import dalvik.system.CloseGuard;
323import dalvik.system.VMRuntime;
324
325import libcore.io.IoUtils;
326
327import org.xmlpull.v1.XmlPullParser;
328import org.xmlpull.v1.XmlPullParserException;
329import org.xmlpull.v1.XmlSerializer;
330
331import java.io.BufferedOutputStream;
332import java.io.ByteArrayInputStream;
333import java.io.ByteArrayOutputStream;
334import java.io.File;
335import java.io.FileDescriptor;
336import java.io.FileInputStream;
337import java.io.FileOutputStream;
338import java.io.FilenameFilter;
339import java.io.IOException;
340import java.io.PrintWriter;
341import java.lang.annotation.Retention;
342import java.lang.annotation.RetentionPolicy;
343import java.nio.charset.StandardCharsets;
344import java.security.DigestException;
345import java.security.DigestInputStream;
346import java.security.MessageDigest;
347import java.security.NoSuchAlgorithmException;
348import java.security.PublicKey;
349import java.security.SecureRandom;
350import java.security.cert.CertificateException;
351import java.util.ArrayList;
352import java.util.Arrays;
353import java.util.Collection;
354import java.util.Collections;
355import java.util.Comparator;
356import java.util.HashMap;
357import java.util.HashSet;
358import java.util.Iterator;
359import java.util.LinkedHashSet;
360import java.util.List;
361import java.util.Map;
362import java.util.Objects;
363import java.util.Set;
364import java.util.concurrent.CountDownLatch;
365import java.util.concurrent.Future;
366import java.util.concurrent.TimeUnit;
367import java.util.concurrent.atomic.AtomicBoolean;
368import java.util.concurrent.atomic.AtomicInteger;
369
370/**
371 * Keep track of all those APKs everywhere.
372 * <p>
373 * Internally there are two important locks:
374 * <ul>
375 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
376 * and other related state. It is a fine-grained lock that should only be held
377 * momentarily, as it's one of the most contended locks in the system.
378 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
379 * operations typically involve heavy lifting of application data on disk. Since
380 * {@code installd} is single-threaded, and it's operations can often be slow,
381 * this lock should never be acquired while already holding {@link #mPackages}.
382 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
383 * holding {@link #mInstallLock}.
384 * </ul>
385 * Many internal methods rely on the caller to hold the appropriate locks, and
386 * this contract is expressed through method name suffixes:
387 * <ul>
388 * <li>fooLI(): the caller must hold {@link #mInstallLock}
389 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
390 * being modified must be frozen
391 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
392 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
393 * </ul>
394 * <p>
395 * Because this class is very central to the platform's security; please run all
396 * CTS and unit tests whenever making modifications:
397 *
398 * <pre>
399 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
400 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
401 * </pre>
402 */
403public class PackageManagerService extends IPackageManager.Stub
404        implements PackageSender {
405    static final String TAG = "PackageManager";
406    public static final boolean DEBUG_SETTINGS = false;
407    static final boolean DEBUG_PREFERRED = false;
408    static final boolean DEBUG_UPGRADE = false;
409    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
410    private static final boolean DEBUG_BACKUP = false;
411    public static final boolean DEBUG_INSTALL = false;
412    public static final boolean DEBUG_REMOVE = true;
413    private static final boolean DEBUG_BROADCASTS = false;
414    private static final boolean DEBUG_SHOW_INFO = false;
415    private static final boolean DEBUG_PACKAGE_INFO = false;
416    private static final boolean DEBUG_INTENT_MATCHING = false;
417    public static final boolean DEBUG_PACKAGE_SCANNING = false;
418    private static final boolean DEBUG_VERIFY = false;
419    private static final boolean DEBUG_FILTERS = false;
420    public static final boolean DEBUG_PERMISSIONS = false;
421    private static final boolean DEBUG_SHARED_LIBRARIES = false;
422    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
423
424    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
425    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
426    // user, but by default initialize to this.
427    public static final boolean DEBUG_DEXOPT = false;
428
429    private static final boolean DEBUG_ABI_SELECTION = false;
430    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
431    private static final boolean DEBUG_TRIAGED_MISSING = false;
432    private static final boolean DEBUG_APP_DATA = false;
433
434    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
435    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
436
437    private static final boolean HIDE_EPHEMERAL_APIS = false;
438
439    private static final boolean ENABLE_FREE_CACHE_V2 =
440            SystemProperties.getBoolean("fw.free_cache_v2", true);
441
442    private static final int RADIO_UID = Process.PHONE_UID;
443    private static final int LOG_UID = Process.LOG_UID;
444    private static final int NFC_UID = Process.NFC_UID;
445    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
446    private static final int SHELL_UID = Process.SHELL_UID;
447    private static final int SE_UID = Process.SE_UID;
448
449    // Suffix used during package installation when copying/moving
450    // package apks to install directory.
451    private static final String INSTALL_PACKAGE_SUFFIX = "-";
452
453    static final int SCAN_NO_DEX = 1<<0;
454    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
455    static final int SCAN_NEW_INSTALL = 1<<2;
456    static final int SCAN_UPDATE_TIME = 1<<3;
457    static final int SCAN_BOOTING = 1<<4;
458    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
459    static final int SCAN_REQUIRE_KNOWN = 1<<7;
460    static final int SCAN_MOVE = 1<<8;
461    static final int SCAN_INITIAL = 1<<9;
462    static final int SCAN_CHECK_ONLY = 1<<10;
463    static final int SCAN_DONT_KILL_APP = 1<<11;
464    static final int SCAN_IGNORE_FROZEN = 1<<12;
465    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
466    static final int SCAN_AS_INSTANT_APP = 1<<14;
467    static final int SCAN_AS_FULL_APP = 1<<15;
468    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
469    static final int SCAN_AS_SYSTEM = 1<<17;
470    static final int SCAN_AS_PRIVILEGED = 1<<18;
471    static final int SCAN_AS_OEM = 1<<19;
472    static final int SCAN_AS_VENDOR = 1<<20;
473    static final int SCAN_AS_PRODUCT = 1<<21;
474
475    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
476            SCAN_NO_DEX,
477            SCAN_UPDATE_SIGNATURE,
478            SCAN_NEW_INSTALL,
479            SCAN_UPDATE_TIME,
480            SCAN_BOOTING,
481            SCAN_DELETE_DATA_ON_FAILURES,
482            SCAN_REQUIRE_KNOWN,
483            SCAN_MOVE,
484            SCAN_INITIAL,
485            SCAN_CHECK_ONLY,
486            SCAN_DONT_KILL_APP,
487            SCAN_IGNORE_FROZEN,
488            SCAN_FIRST_BOOT_OR_UPGRADE,
489            SCAN_AS_INSTANT_APP,
490            SCAN_AS_FULL_APP,
491            SCAN_AS_VIRTUAL_PRELOAD,
492    })
493    @Retention(RetentionPolicy.SOURCE)
494    public @interface ScanFlags {}
495
496    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
497    /** Extension of the compressed packages */
498    public final static String COMPRESSED_EXTENSION = ".gz";
499    /** Suffix of stub packages on the system partition */
500    public final static String STUB_SUFFIX = "-Stub";
501
502    private static final int[] EMPTY_INT_ARRAY = new int[0];
503
504    private static final int TYPE_UNKNOWN = 0;
505    private static final int TYPE_ACTIVITY = 1;
506    private static final int TYPE_RECEIVER = 2;
507    private static final int TYPE_SERVICE = 3;
508    private static final int TYPE_PROVIDER = 4;
509    @IntDef(prefix = { "TYPE_" }, value = {
510            TYPE_UNKNOWN,
511            TYPE_ACTIVITY,
512            TYPE_RECEIVER,
513            TYPE_SERVICE,
514            TYPE_PROVIDER,
515    })
516    @Retention(RetentionPolicy.SOURCE)
517    public @interface ComponentType {}
518
519    /**
520     * Timeout (in milliseconds) after which the watchdog should declare that
521     * our handler thread is wedged.  The usual default for such things is one
522     * minute but we sometimes do very lengthy I/O operations on this thread,
523     * such as installing multi-gigabyte applications, so ours needs to be longer.
524     */
525    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
526
527    /**
528     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
529     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
530     * settings entry if available, otherwise we use the hardcoded default.  If it's been
531     * more than this long since the last fstrim, we force one during the boot sequence.
532     *
533     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
534     * one gets run at the next available charging+idle time.  This final mandatory
535     * no-fstrim check kicks in only of the other scheduling criteria is never met.
536     */
537    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
538
539    /**
540     * Whether verification is enabled by default.
541     */
542    private static final boolean DEFAULT_VERIFY_ENABLE = true;
543
544    /**
545     * The default maximum time to wait for the verification agent to return in
546     * milliseconds.
547     */
548    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
549
550    /**
551     * The default response for package verification timeout.
552     *
553     * This can be either PackageManager.VERIFICATION_ALLOW or
554     * PackageManager.VERIFICATION_REJECT.
555     */
556    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
557
558    public static final String PLATFORM_PACKAGE_NAME = "android";
559
560    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
561
562    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
563            DEFAULT_CONTAINER_PACKAGE,
564            "com.android.defcontainer.DefaultContainerService");
565
566    private static final String KILL_APP_REASON_GIDS_CHANGED =
567            "permission grant or revoke changed gids";
568
569    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
570            "permissions revoked";
571
572    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
573
574    private static final String PACKAGE_SCHEME = "package";
575
576    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
577
578    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
579
580    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
581
582    /** Canonical intent used to identify what counts as a "web browser" app */
583    private static final Intent sBrowserIntent;
584    static {
585        sBrowserIntent = new Intent();
586        sBrowserIntent.setAction(Intent.ACTION_VIEW);
587        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
588        sBrowserIntent.setData(Uri.parse("http:"));
589        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
590    }
591
592    /**
593     * The set of all protected actions [i.e. those actions for which a high priority
594     * intent filter is disallowed].
595     */
596    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
597    static {
598        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
599        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
600        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
601        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
602    }
603
604    // Compilation reasons.
605    public static final int REASON_UNKNOWN = -1;
606    public static final int REASON_FIRST_BOOT = 0;
607    public static final int REASON_BOOT = 1;
608    public static final int REASON_INSTALL = 2;
609    public static final int REASON_BACKGROUND_DEXOPT = 3;
610    public static final int REASON_AB_OTA = 4;
611    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
612    public static final int REASON_SHARED = 6;
613
614    public static final int REASON_LAST = REASON_SHARED;
615
616    /**
617     * Version number for the package parser cache. Increment this whenever the format or
618     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
619     */
620    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
621
622    /**
623     * Whether the package parser cache is enabled.
624     */
625    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
626
627    /**
628     * Permissions required in order to receive instant application lifecycle broadcasts.
629     */
630    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
631            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
632
633    final ServiceThread mHandlerThread;
634
635    final PackageHandler mHandler;
636
637    private final ProcessLoggingHandler mProcessLoggingHandler;
638
639    /**
640     * Messages for {@link #mHandler} that need to wait for system ready before
641     * being dispatched.
642     */
643    private ArrayList<Message> mPostSystemReadyMessages;
644
645    final int mSdkVersion = Build.VERSION.SDK_INT;
646
647    final Context mContext;
648    final boolean mFactoryTest;
649    final boolean mOnlyCore;
650    final DisplayMetrics mMetrics;
651    final int mDefParseFlags;
652    final String[] mSeparateProcesses;
653    final boolean mIsUpgrade;
654    final boolean mIsPreNUpgrade;
655    final boolean mIsPreNMR1Upgrade;
656
657    // Have we told the Activity Manager to whitelist the default container service by uid yet?
658    @GuardedBy("mPackages")
659    boolean mDefaultContainerWhitelisted = false;
660
661    @GuardedBy("mPackages")
662    private boolean mDexOptDialogShown;
663
664    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
665    // LOCK HELD.  Can be called with mInstallLock held.
666    @GuardedBy("mInstallLock")
667    final Installer mInstaller;
668
669    /** Directory where installed applications are stored */
670    private static final File sAppInstallDir =
671            new File(Environment.getDataDirectory(), "app");
672    /** Directory where installed application's 32-bit native libraries are copied. */
673    private static final File sAppLib32InstallDir =
674            new File(Environment.getDataDirectory(), "app-lib");
675    /** Directory where code and non-resource assets of forward-locked applications are stored */
676    private static final File sDrmAppPrivateInstallDir =
677            new File(Environment.getDataDirectory(), "app-private");
678
679    // ----------------------------------------------------------------
680
681    // Lock for state used when installing and doing other long running
682    // operations.  Methods that must be called with this lock held have
683    // the suffix "LI".
684    final Object mInstallLock = new Object();
685
686    // ----------------------------------------------------------------
687
688    // Keys are String (package name), values are Package.  This also serves
689    // as the lock for the global state.  Methods that must be called with
690    // this lock held have the prefix "LP".
691    @GuardedBy("mPackages")
692    final ArrayMap<String, PackageParser.Package> mPackages =
693            new ArrayMap<String, PackageParser.Package>();
694
695    final ArrayMap<String, Set<String>> mKnownCodebase =
696            new ArrayMap<String, Set<String>>();
697
698    // Keys are isolated uids and values are the uid of the application
699    // that created the isolated proccess.
700    @GuardedBy("mPackages")
701    final SparseIntArray mIsolatedOwners = new SparseIntArray();
702
703    /**
704     * Tracks new system packages [received in an OTA] that we expect to
705     * find updated user-installed versions. Keys are package name, values
706     * are package location.
707     */
708    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709    /**
710     * Tracks high priority intent filters for protected actions. During boot, certain
711     * filter actions are protected and should never be allowed to have a high priority
712     * intent filter for them. However, there is one, and only one exception -- the
713     * setup wizard. It must be able to define a high priority intent filter for these
714     * actions to ensure there are no escapes from the wizard. We need to delay processing
715     * of these during boot as we need to look at all of the system packages in order
716     * to know which component is the setup wizard.
717     */
718    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719    /**
720     * Whether or not processing protected filters should be deferred.
721     */
722    private boolean mDeferProtectedFilters = true;
723
724    /**
725     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726     */
727    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728    /**
729     * Whether or not system app permissions should be promoted from install to runtime.
730     */
731    boolean mPromoteSystemApps;
732
733    @GuardedBy("mPackages")
734    final Settings mSettings;
735
736    /**
737     * Set of package names that are currently "frozen", which means active
738     * surgery is being done on the code/data for that package. The platform
739     * will refuse to launch frozen packages to avoid race conditions.
740     *
741     * @see PackageFreezer
742     */
743    @GuardedBy("mPackages")
744    final ArraySet<String> mFrozenPackages = new ArraySet<>();
745
746    final ProtectedPackages mProtectedPackages;
747
748    @GuardedBy("mLoadedVolumes")
749    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
750
751    boolean mFirstBoot;
752
753    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754
755    @GuardedBy("mAvailableFeatures")
756    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
757
758    private final InstantAppRegistry mInstantAppRegistry;
759
760    @GuardedBy("mPackages")
761    int mChangedPackagesSequenceNumber;
762    /**
763     * List of changed [installed, removed or updated] packages.
764     * mapping from user id -> sequence number -> package name
765     */
766    @GuardedBy("mPackages")
767    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
768    /**
769     * The sequence number of the last change to a package.
770     * mapping from user id -> package name -> sequence number
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
774
775    @GuardedBy("mPackages")
776    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
777
778    class PackageParserCallback implements PackageParser.Callback {
779        @Override public final boolean hasFeature(String feature) {
780            return PackageManagerService.this.hasSystemFeature(feature, 0);
781        }
782
783        final List<PackageParser.Package> getStaticOverlayPackages(
784                Collection<PackageParser.Package> allPackages, String targetPackageName) {
785            if ("android".equals(targetPackageName)) {
786                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
787                // native AssetManager.
788                return null;
789            }
790
791            List<PackageParser.Package> overlayPackages = null;
792            for (PackageParser.Package p : allPackages) {
793                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
794                    if (overlayPackages == null) {
795                        overlayPackages = new ArrayList<PackageParser.Package>();
796                    }
797                    overlayPackages.add(p);
798                }
799            }
800            if (overlayPackages != null) {
801                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
802                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
803                        return p1.mOverlayPriority - p2.mOverlayPriority;
804                    }
805                };
806                Collections.sort(overlayPackages, cmp);
807            }
808            return overlayPackages;
809        }
810
811        final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
812                String targetPath) {
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            List<PackageParser.Package> overlayPackages;
849            synchronized (mInstallLock) {
850                synchronized (mPackages) {
851                    overlayPackages = getStaticOverlayPackages(
852                            mPackages.values(), targetPackageName);
853                }
854                // It is safe to keep overlayPackages without holding mPackages because static overlay
855                // packages can't be uninstalled or disabled.
856                return getStaticOverlayPaths(overlayPackages, targetPath);
857            }
858        }
859
860        @Override public final String[] getOverlayApks(String targetPackageName) {
861            return getStaticOverlayPaths(targetPackageName, null);
862        }
863
864        @Override public final String[] getOverlayPaths(String targetPackageName,
865                String targetPath) {
866            return getStaticOverlayPaths(targetPackageName, targetPath);
867        }
868    }
869
870    class ParallelPackageParserCallback extends PackageParserCallback {
871        List<PackageParser.Package> mOverlayPackages = null;
872
873        void findStaticOverlayPackages() {
874            synchronized (mPackages) {
875                for (PackageParser.Package p : mPackages.values()) {
876                    if (p.mOverlayIsStatic) {
877                        if (mOverlayPackages == null) {
878                            mOverlayPackages = new ArrayList<PackageParser.Package>();
879                        }
880                        mOverlayPackages.add(p);
881                    }
882                }
883            }
884        }
885
886        @Override
887        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
888            // We can trust mOverlayPackages without holding mPackages because package uninstall
889            // can't happen while running parallel parsing.
890            // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
891            // because mInstallLock is held before running parallel parsing.
892            // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
893            return mOverlayPackages == null ? null :
894                    getStaticOverlayPaths(
895                            getStaticOverlayPackages(mOverlayPackages, targetPackageName),
896                            targetPath);
897        }
898    }
899
900    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
901    final ParallelPackageParserCallback mParallelPackageParserCallback =
902            new ParallelPackageParserCallback();
903
904    public static final class SharedLibraryEntry {
905        public final @Nullable String path;
906        public final @Nullable String apk;
907        public final @NonNull SharedLibraryInfo info;
908
909        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
910                String declaringPackageName, long declaringPackageVersionCode) {
911            path = _path;
912            apk = _apk;
913            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
914                    declaringPackageName, declaringPackageVersionCode), null);
915        }
916    }
917
918    // Currently known shared libraries.
919    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
920    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
921            new ArrayMap<>();
922
923    // All available activities, for your resolving pleasure.
924    final ActivityIntentResolver mActivities =
925            new ActivityIntentResolver();
926
927    // All available receivers, for your resolving pleasure.
928    final ActivityIntentResolver mReceivers =
929            new ActivityIntentResolver();
930
931    // All available services, for your resolving pleasure.
932    final ServiceIntentResolver mServices = new ServiceIntentResolver();
933
934    // All available providers, for your resolving pleasure.
935    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
936
937    // Mapping from provider base names (first directory in content URI codePath)
938    // to the provider information.
939    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
940            new ArrayMap<String, PackageParser.Provider>();
941
942    // Mapping from instrumentation class names to info about them.
943    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
944            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
945
946    // Packages whose data we have transfered into another package, thus
947    // should no longer exist.
948    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
949
950    // Broadcast actions that are only available to the system.
951    @GuardedBy("mProtectedBroadcasts")
952    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
953
954    /** List of packages waiting for verification. */
955    final SparseArray<PackageVerificationState> mPendingVerification
956            = new SparseArray<PackageVerificationState>();
957
958    final PackageInstallerService mInstallerService;
959
960    final ArtManagerService mArtManagerService;
961
962    private final PackageDexOptimizer mPackageDexOptimizer;
963    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
964    // is used by other apps).
965    private final DexManager mDexManager;
966
967    private AtomicInteger mNextMoveId = new AtomicInteger();
968    private final MoveCallbacks mMoveCallbacks;
969
970    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
971
972    // Cache of users who need badging.
973    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
974
975    /** Token for keys in mPendingVerification. */
976    private int mPendingVerificationToken = 0;
977
978    volatile boolean mSystemReady;
979    volatile boolean mSafeMode;
980    volatile boolean mHasSystemUidErrors;
981    private volatile boolean mWebInstantAppsDisabled;
982
983    ApplicationInfo mAndroidApplication;
984    final ActivityInfo mResolveActivity = new ActivityInfo();
985    final ResolveInfo mResolveInfo = new ResolveInfo();
986    ComponentName mResolveComponentName;
987    PackageParser.Package mPlatformPackage;
988    ComponentName mCustomResolverComponentName;
989
990    boolean mResolverReplaced = false;
991
992    private final @Nullable ComponentName mIntentFilterVerifierComponent;
993    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
994
995    private int mIntentFilterVerificationToken = 0;
996
997    /** The service connection to the ephemeral resolver */
998    final InstantAppResolverConnection mInstantAppResolverConnection;
999    /** Component used to show resolver settings for Instant Apps */
1000    final ComponentName mInstantAppResolverSettingsComponent;
1001
1002    /** Activity used to install instant applications */
1003    ActivityInfo mInstantAppInstallerActivity;
1004    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1005
1006    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1007            = new SparseArray<IntentFilterVerificationState>();
1008
1009    // TODO remove this and go through mPermissonManager directly
1010    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1011    private final PermissionManagerInternal mPermissionManager;
1012
1013    // List of packages names to keep cached, even if they are uninstalled for all users
1014    private List<String> mKeepUninstalledPackages;
1015
1016    private UserManagerInternal mUserManagerInternal;
1017    private ActivityManagerInternal mActivityManagerInternal;
1018
1019    private DeviceIdleController.LocalService mDeviceIdleController;
1020
1021    private File mCacheDir;
1022
1023    private Future<?> mPrepareAppDataFuture;
1024
1025    private static class IFVerificationParams {
1026        PackageParser.Package pkg;
1027        boolean replacing;
1028        int userId;
1029        int verifierUid;
1030
1031        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1032                int _userId, int _verifierUid) {
1033            pkg = _pkg;
1034            replacing = _replacing;
1035            userId = _userId;
1036            replacing = _replacing;
1037            verifierUid = _verifierUid;
1038        }
1039    }
1040
1041    private interface IntentFilterVerifier<T extends IntentFilter> {
1042        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1043                                               T filter, String packageName);
1044        void startVerifications(int userId);
1045        void receiveVerificationResponse(int verificationId);
1046    }
1047
1048    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1049        private Context mContext;
1050        private ComponentName mIntentFilterVerifierComponent;
1051        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1052
1053        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1054            mContext = context;
1055            mIntentFilterVerifierComponent = verifierComponent;
1056        }
1057
1058        private String getDefaultScheme() {
1059            return IntentFilter.SCHEME_HTTPS;
1060        }
1061
1062        @Override
1063        public void startVerifications(int userId) {
1064            // Launch verifications requests
1065            int count = mCurrentIntentFilterVerifications.size();
1066            for (int n=0; n<count; n++) {
1067                int verificationId = mCurrentIntentFilterVerifications.get(n);
1068                final IntentFilterVerificationState ivs =
1069                        mIntentFilterVerificationStates.get(verificationId);
1070
1071                String packageName = ivs.getPackageName();
1072
1073                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1074                final int filterCount = filters.size();
1075                ArraySet<String> domainsSet = new ArraySet<>();
1076                for (int m=0; m<filterCount; m++) {
1077                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1078                    domainsSet.addAll(filter.getHostsList());
1079                }
1080                synchronized (mPackages) {
1081                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1082                            packageName, domainsSet) != null) {
1083                        scheduleWriteSettingsLocked();
1084                    }
1085                }
1086                sendVerificationRequest(verificationId, ivs);
1087            }
1088            mCurrentIntentFilterVerifications.clear();
1089        }
1090
1091        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1092            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1095                    verificationId);
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1098                    getDefaultScheme());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1101                    ivs.getHostsString());
1102            verificationIntent.putExtra(
1103                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1104                    ivs.getPackageName());
1105            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1106            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1107
1108            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1109            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1110                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1111                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1112
1113            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1114            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1115                    "Sending IntentFilter verification broadcast");
1116        }
1117
1118        public void receiveVerificationResponse(int verificationId) {
1119            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1120
1121            final boolean verified = ivs.isVerified();
1122
1123            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1124            final int count = filters.size();
1125            if (DEBUG_DOMAIN_VERIFICATION) {
1126                Slog.i(TAG, "Received verification response " + verificationId
1127                        + " for " + count + " filters, verified=" + verified);
1128            }
1129            for (int n=0; n<count; n++) {
1130                PackageParser.ActivityIntentInfo filter = filters.get(n);
1131                filter.setVerified(verified);
1132
1133                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1134                        + " verified with result:" + verified + " and hosts:"
1135                        + ivs.getHostsString());
1136            }
1137
1138            mIntentFilterVerificationStates.remove(verificationId);
1139
1140            final String packageName = ivs.getPackageName();
1141            IntentFilterVerificationInfo ivi = null;
1142
1143            synchronized (mPackages) {
1144                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1145            }
1146            if (ivi == null) {
1147                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1148                        + verificationId + " packageName:" + packageName);
1149                return;
1150            }
1151            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1152                    "Updating IntentFilterVerificationInfo for package " + packageName
1153                            +" verificationId:" + verificationId);
1154
1155            synchronized (mPackages) {
1156                if (verified) {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1158                } else {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1160                }
1161                scheduleWriteSettingsLocked();
1162
1163                final int userId = ivs.getUserId();
1164                if (userId != UserHandle.USER_ALL) {
1165                    final int userStatus =
1166                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1167
1168                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1169                    boolean needUpdate = false;
1170
1171                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1172                    // already been set by the User thru the Disambiguation dialog
1173                    switch (userStatus) {
1174                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1175                            if (verified) {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1177                            } else {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1179                            }
1180                            needUpdate = true;
1181                            break;
1182
1183                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1184                            if (verified) {
1185                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1186                                needUpdate = true;
1187                            }
1188                            break;
1189
1190                        default:
1191                            // Nothing to do
1192                    }
1193
1194                    if (needUpdate) {
1195                        mSettings.updateIntentFilterVerificationStatusLPw(
1196                                packageName, updatedStatus, userId);
1197                        scheduleWritePackageRestrictionsLocked(userId);
1198                    }
1199                }
1200            }
1201        }
1202
1203        @Override
1204        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1205                    ActivityIntentInfo filter, String packageName) {
1206            if (!hasValidDomains(filter)) {
1207                return false;
1208            }
1209            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1210            if (ivs == null) {
1211                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1212                        packageName);
1213            }
1214            if (DEBUG_DOMAIN_VERIFICATION) {
1215                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1216            }
1217            ivs.addFilter(filter);
1218            return true;
1219        }
1220
1221        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1222                int userId, int verificationId, String packageName) {
1223            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1224                    verifierUid, userId, packageName);
1225            ivs.setPendingState();
1226            synchronized (mPackages) {
1227                mIntentFilterVerificationStates.append(verificationId, ivs);
1228                mCurrentIntentFilterVerifications.add(verificationId);
1229            }
1230            return ivs;
1231        }
1232    }
1233
1234    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1235        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1236                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1237                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1238    }
1239
1240    // Set of pending broadcasts for aggregating enable/disable of components.
1241    static class PendingPackageBroadcasts {
1242        // for each user id, a map of <package name -> components within that package>
1243        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1244
1245        public PendingPackageBroadcasts() {
1246            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1247        }
1248
1249        public ArrayList<String> get(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1251            return packages.get(packageName);
1252        }
1253
1254        public void put(int userId, String packageName, ArrayList<String> components) {
1255            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1256            packages.put(packageName, components);
1257        }
1258
1259        public void remove(int userId, String packageName) {
1260            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1261            if (packages != null) {
1262                packages.remove(packageName);
1263            }
1264        }
1265
1266        public void remove(int userId) {
1267            mUidMap.remove(userId);
1268        }
1269
1270        public int userIdCount() {
1271            return mUidMap.size();
1272        }
1273
1274        public int userIdAt(int n) {
1275            return mUidMap.keyAt(n);
1276        }
1277
1278        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1279            return mUidMap.get(userId);
1280        }
1281
1282        public int size() {
1283            // total number of pending broadcast entries across all userIds
1284            int num = 0;
1285            for (int i = 0; i< mUidMap.size(); i++) {
1286                num += mUidMap.valueAt(i).size();
1287            }
1288            return num;
1289        }
1290
1291        public void clear() {
1292            mUidMap.clear();
1293        }
1294
1295        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1296            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1297            if (map == null) {
1298                map = new ArrayMap<String, ArrayList<String>>();
1299                mUidMap.put(userId, map);
1300            }
1301            return map;
1302        }
1303    }
1304    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1305
1306    // Service Connection to remote media container service to copy
1307    // package uri's from external media onto secure containers
1308    // or internal storage.
1309    private IMediaContainerService mContainerService = null;
1310
1311    static final int SEND_PENDING_BROADCAST = 1;
1312    static final int MCS_BOUND = 3;
1313    static final int END_COPY = 4;
1314    static final int INIT_COPY = 5;
1315    static final int MCS_UNBIND = 6;
1316    static final int START_CLEANING_PACKAGE = 7;
1317    static final int FIND_INSTALL_LOC = 8;
1318    static final int POST_INSTALL = 9;
1319    static final int MCS_RECONNECT = 10;
1320    static final int MCS_GIVE_UP = 11;
1321    static final int WRITE_SETTINGS = 13;
1322    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1323    static final int PACKAGE_VERIFIED = 15;
1324    static final int CHECK_PENDING_VERIFICATION = 16;
1325    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1326    static final int INTENT_FILTER_VERIFIED = 18;
1327    static final int WRITE_PACKAGE_LIST = 19;
1328    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1329
1330    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1331
1332    // Delay time in millisecs
1333    static final int BROADCAST_DELAY = 10 * 1000;
1334
1335    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1336            2 * 60 * 60 * 1000L; /* two hours */
1337
1338    static UserManagerService sUserManager;
1339
1340    // Stores a list of users whose package restrictions file needs to be updated
1341    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1342
1343    final private DefaultContainerConnection mDefContainerConn =
1344            new DefaultContainerConnection();
1345    class DefaultContainerConnection implements ServiceConnection {
1346        public void onServiceConnected(ComponentName name, IBinder service) {
1347            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1348            final IMediaContainerService imcs = IMediaContainerService.Stub
1349                    .asInterface(Binder.allowBlocking(service));
1350            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1351        }
1352
1353        public void onServiceDisconnected(ComponentName name) {
1354            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1355        }
1356    }
1357
1358    // Recordkeeping of restore-after-install operations that are currently in flight
1359    // between the Package Manager and the Backup Manager
1360    static class PostInstallData {
1361        public InstallArgs args;
1362        public PackageInstalledInfo res;
1363
1364        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1365            args = _a;
1366            res = _r;
1367        }
1368    }
1369
1370    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1371    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1372
1373    // XML tags for backup/restore of various bits of state
1374    private static final String TAG_PREFERRED_BACKUP = "pa";
1375    private static final String TAG_DEFAULT_APPS = "da";
1376    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1377
1378    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1379    private static final String TAG_ALL_GRANTS = "rt-grants";
1380    private static final String TAG_GRANT = "grant";
1381    private static final String ATTR_PACKAGE_NAME = "pkg";
1382
1383    private static final String TAG_PERMISSION = "perm";
1384    private static final String ATTR_PERMISSION_NAME = "name";
1385    private static final String ATTR_IS_GRANTED = "g";
1386    private static final String ATTR_USER_SET = "set";
1387    private static final String ATTR_USER_FIXED = "fixed";
1388    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1389
1390    // System/policy permission grants are not backed up
1391    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1392            FLAG_PERMISSION_POLICY_FIXED
1393            | FLAG_PERMISSION_SYSTEM_FIXED
1394            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1395
1396    // And we back up these user-adjusted states
1397    private static final int USER_RUNTIME_GRANT_MASK =
1398            FLAG_PERMISSION_USER_SET
1399            | FLAG_PERMISSION_USER_FIXED
1400            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1401
1402    final @Nullable String mRequiredVerifierPackage;
1403    final @NonNull String mRequiredInstallerPackage;
1404    final @NonNull String mRequiredUninstallerPackage;
1405    final @Nullable String mSetupWizardPackage;
1406    final @Nullable String mStorageManagerPackage;
1407    final @Nullable String mSystemTextClassifierPackage;
1408    final @NonNull String mServicesSystemSharedLibraryPackageName;
1409    final @NonNull String mSharedSystemSharedLibraryPackageName;
1410
1411    private final PackageUsage mPackageUsage = new PackageUsage();
1412    private final CompilerStats mCompilerStats = new CompilerStats();
1413
1414    class PackageHandler extends Handler {
1415        private boolean mBound = false;
1416        final ArrayList<HandlerParams> mPendingInstalls =
1417            new ArrayList<HandlerParams>();
1418
1419        private boolean connectToService() {
1420            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1421                    " DefaultContainerService");
1422            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1425                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427                mBound = true;
1428                return true;
1429            }
1430            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431            return false;
1432        }
1433
1434        private void disconnectService() {
1435            mContainerService = null;
1436            mBound = false;
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1438            mContext.unbindService(mDefContainerConn);
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440        }
1441
1442        PackageHandler(Looper looper) {
1443            super(looper);
1444        }
1445
1446        public void handleMessage(Message msg) {
1447            try {
1448                doHandleMessage(msg);
1449            } finally {
1450                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1451            }
1452        }
1453
1454        void doHandleMessage(Message msg) {
1455            switch (msg.what) {
1456                case INIT_COPY: {
1457                    HandlerParams params = (HandlerParams) msg.obj;
1458                    int idx = mPendingInstalls.size();
1459                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1460                    // If a bind was already initiated we dont really
1461                    // need to do anything. The pending install
1462                    // will be processed later on.
1463                    if (!mBound) {
1464                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1465                                System.identityHashCode(mHandler));
1466                        // If this is the only one pending we might
1467                        // have to bind to the service again.
1468                        if (!connectToService()) {
1469                            Slog.e(TAG, "Failed to bind to media container service");
1470                            params.serviceError();
1471                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1472                                    System.identityHashCode(mHandler));
1473                            if (params.traceMethod != null) {
1474                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1475                                        params.traceCookie);
1476                            }
1477                            return;
1478                        } else {
1479                            // Once we bind to the service, the first
1480                            // pending request will be processed.
1481                            mPendingInstalls.add(idx, params);
1482                        }
1483                    } else {
1484                        mPendingInstalls.add(idx, params);
1485                        // Already bound to the service. Just make
1486                        // sure we trigger off processing the first request.
1487                        if (idx == 0) {
1488                            mHandler.sendEmptyMessage(MCS_BOUND);
1489                        }
1490                    }
1491                    break;
1492                }
1493                case MCS_BOUND: {
1494                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1495                    if (msg.obj != null) {
1496                        mContainerService = (IMediaContainerService) msg.obj;
1497                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1498                                System.identityHashCode(mHandler));
1499                    }
1500                    if (mContainerService == null) {
1501                        if (!mBound) {
1502                            // Something seriously wrong since we are not bound and we are not
1503                            // waiting for connection. Bail out.
1504                            Slog.e(TAG, "Cannot bind to media container service");
1505                            for (HandlerParams params : mPendingInstalls) {
1506                                // Indicate service bind error
1507                                params.serviceError();
1508                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                        System.identityHashCode(params));
1510                                if (params.traceMethod != null) {
1511                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1512                                            params.traceMethod, params.traceCookie);
1513                                }
1514                                return;
1515                            }
1516                            mPendingInstalls.clear();
1517                        } else {
1518                            Slog.w(TAG, "Waiting to connect to media container service");
1519                        }
1520                    } else if (mPendingInstalls.size() > 0) {
1521                        HandlerParams params = mPendingInstalls.get(0);
1522                        if (params != null) {
1523                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1524                                    System.identityHashCode(params));
1525                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1526                            if (params.startCopy()) {
1527                                // We are done...  look for more work or to
1528                                // go idle.
1529                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1530                                        "Checking for more work or unbind...");
1531                                // Delete pending install
1532                                if (mPendingInstalls.size() > 0) {
1533                                    mPendingInstalls.remove(0);
1534                                }
1535                                if (mPendingInstalls.size() == 0) {
1536                                    if (mBound) {
1537                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1538                                                "Posting delayed MCS_UNBIND");
1539                                        removeMessages(MCS_UNBIND);
1540                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1541                                        // Unbind after a little delay, to avoid
1542                                        // continual thrashing.
1543                                        sendMessageDelayed(ubmsg, 10000);
1544                                    }
1545                                } else {
1546                                    // There are more pending requests in queue.
1547                                    // Just post MCS_BOUND message to trigger processing
1548                                    // of next pending install.
1549                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1550                                            "Posting MCS_BOUND for next work");
1551                                    mHandler.sendEmptyMessage(MCS_BOUND);
1552                                }
1553                            }
1554                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1555                        }
1556                    } else {
1557                        // Should never happen ideally.
1558                        Slog.w(TAG, "Empty queue");
1559                    }
1560                    break;
1561                }
1562                case MCS_RECONNECT: {
1563                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1564                    if (mPendingInstalls.size() > 0) {
1565                        if (mBound) {
1566                            disconnectService();
1567                        }
1568                        if (!connectToService()) {
1569                            Slog.e(TAG, "Failed to bind to media container service");
1570                            for (HandlerParams params : mPendingInstalls) {
1571                                // Indicate service bind error
1572                                params.serviceError();
1573                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1574                                        System.identityHashCode(params));
1575                            }
1576                            mPendingInstalls.clear();
1577                        }
1578                    }
1579                    break;
1580                }
1581                case MCS_UNBIND: {
1582                    // If there is no actual work left, then time to unbind.
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1584
1585                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1586                        if (mBound) {
1587                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1588
1589                            disconnectService();
1590                        }
1591                    } else if (mPendingInstalls.size() > 0) {
1592                        // There are more pending requests in queue.
1593                        // Just post MCS_BOUND message to trigger processing
1594                        // of next pending install.
1595                        mHandler.sendEmptyMessage(MCS_BOUND);
1596                    }
1597
1598                    break;
1599                }
1600                case MCS_GIVE_UP: {
1601                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1602                    HandlerParams params = mPendingInstalls.remove(0);
1603                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1604                            System.identityHashCode(params));
1605                    break;
1606                }
1607                case SEND_PENDING_BROADCAST: {
1608                    String packages[];
1609                    ArrayList<String> components[];
1610                    int size = 0;
1611                    int uids[];
1612                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1613                    synchronized (mPackages) {
1614                        if (mPendingBroadcasts == null) {
1615                            return;
1616                        }
1617                        size = mPendingBroadcasts.size();
1618                        if (size <= 0) {
1619                            // Nothing to be done. Just return
1620                            return;
1621                        }
1622                        packages = new String[size];
1623                        components = new ArrayList[size];
1624                        uids = new int[size];
1625                        int i = 0;  // filling out the above arrays
1626
1627                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1628                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1629                            Iterator<Map.Entry<String, ArrayList<String>>> it
1630                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1631                                            .entrySet().iterator();
1632                            while (it.hasNext() && i < size) {
1633                                Map.Entry<String, ArrayList<String>> ent = it.next();
1634                                packages[i] = ent.getKey();
1635                                components[i] = ent.getValue();
1636                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1637                                uids[i] = (ps != null)
1638                                        ? UserHandle.getUid(packageUserId, ps.appId)
1639                                        : -1;
1640                                i++;
1641                            }
1642                        }
1643                        size = i;
1644                        mPendingBroadcasts.clear();
1645                    }
1646                    // Send broadcasts
1647                    for (int i = 0; i < size; i++) {
1648                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1649                    }
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1651                    break;
1652                }
1653                case START_CLEANING_PACKAGE: {
1654                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1655                    final String packageName = (String)msg.obj;
1656                    final int userId = msg.arg1;
1657                    final boolean andCode = msg.arg2 != 0;
1658                    synchronized (mPackages) {
1659                        if (userId == UserHandle.USER_ALL) {
1660                            int[] users = sUserManager.getUserIds();
1661                            for (int user : users) {
1662                                mSettings.addPackageToCleanLPw(
1663                                        new PackageCleanItem(user, packageName, andCode));
1664                            }
1665                        } else {
1666                            mSettings.addPackageToCleanLPw(
1667                                    new PackageCleanItem(userId, packageName, andCode));
1668                        }
1669                    }
1670                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1671                    startCleaningPackages();
1672                } break;
1673                case POST_INSTALL: {
1674                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1675
1676                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1677                    final boolean didRestore = (msg.arg2 != 0);
1678                    mRunningInstalls.delete(msg.arg1);
1679
1680                    if (data != null) {
1681                        InstallArgs args = data.args;
1682                        PackageInstalledInfo parentRes = data.res;
1683
1684                        final boolean grantPermissions = (args.installFlags
1685                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1686                        final boolean killApp = (args.installFlags
1687                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1688                        final boolean virtualPreload = ((args.installFlags
1689                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1690                        final String[] grantedPermissions = args.installGrantPermissions;
1691
1692                        // Handle the parent package
1693                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1694                                virtualPreload, grantedPermissions, didRestore,
1695                                args.installerPackageName, args.observer);
1696
1697                        // Handle the child packages
1698                        final int childCount = (parentRes.addedChildPackages != null)
1699                                ? parentRes.addedChildPackages.size() : 0;
1700                        for (int i = 0; i < childCount; i++) {
1701                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1702                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1703                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1704                                    args.installerPackageName, args.observer);
1705                        }
1706
1707                        // Log tracing if needed
1708                        if (args.traceMethod != null) {
1709                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1710                                    args.traceCookie);
1711                        }
1712                    } else {
1713                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1714                    }
1715
1716                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1717                } break;
1718                case WRITE_SETTINGS: {
1719                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1720                    synchronized (mPackages) {
1721                        removeMessages(WRITE_SETTINGS);
1722                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1723                        mSettings.writeLPr();
1724                        mDirtyUsers.clear();
1725                    }
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1727                } break;
1728                case WRITE_PACKAGE_RESTRICTIONS: {
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730                    synchronized (mPackages) {
1731                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732                        for (int userId : mDirtyUsers) {
1733                            mSettings.writePackageRestrictionsLPr(userId);
1734                        }
1735                        mDirtyUsers.clear();
1736                    }
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1738                } break;
1739                case WRITE_PACKAGE_LIST: {
1740                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1741                    synchronized (mPackages) {
1742                        removeMessages(WRITE_PACKAGE_LIST);
1743                        mSettings.writePackageListLPr(msg.arg1);
1744                    }
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1746                } break;
1747                case CHECK_PENDING_VERIFICATION: {
1748                    final int verificationId = msg.arg1;
1749                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1750
1751                    if ((state != null) && !state.timeoutExtended()) {
1752                        final InstallArgs args = state.getInstallArgs();
1753                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1754
1755                        Slog.i(TAG, "Verification timed out for " + originUri);
1756                        mPendingVerification.remove(verificationId);
1757
1758                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1759
1760                        final UserHandle user = args.getUser();
1761                        if (getDefaultVerificationResponse(user)
1762                                == PackageManager.VERIFICATION_ALLOW) {
1763                            Slog.i(TAG, "Continuing with installation of " + originUri);
1764                            state.setVerifierResponse(Binder.getCallingUid(),
1765                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1766                            broadcastPackageVerified(verificationId, originUri,
1767                                    PackageManager.VERIFICATION_ALLOW, user);
1768                            try {
1769                                ret = args.copyApk(mContainerService, true);
1770                            } catch (RemoteException e) {
1771                                Slog.e(TAG, "Could not contact the ContainerService");
1772                            }
1773                        } else {
1774                            broadcastPackageVerified(verificationId, originUri,
1775                                    PackageManager.VERIFICATION_REJECT, user);
1776                        }
1777
1778                        Trace.asyncTraceEnd(
1779                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1780
1781                        processPendingInstall(args, ret);
1782                        mHandler.sendEmptyMessage(MCS_UNBIND);
1783                    }
1784                    break;
1785                }
1786                case PACKAGE_VERIFIED: {
1787                    final int verificationId = msg.arg1;
1788
1789                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1790                    if (state == null) {
1791                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1792                        break;
1793                    }
1794
1795                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1796
1797                    state.setVerifierResponse(response.callerUid, response.code);
1798
1799                    if (state.isVerificationComplete()) {
1800                        mPendingVerification.remove(verificationId);
1801
1802                        final InstallArgs args = state.getInstallArgs();
1803                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1804
1805                        int ret;
1806                        if (state.isInstallAllowed()) {
1807                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1808                            broadcastPackageVerified(verificationId, originUri,
1809                                    response.code, state.getInstallArgs().getUser());
1810                            try {
1811                                ret = args.copyApk(mContainerService, true);
1812                            } catch (RemoteException e) {
1813                                Slog.e(TAG, "Could not contact the ContainerService");
1814                            }
1815                        } else {
1816                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1817                        }
1818
1819                        Trace.asyncTraceEnd(
1820                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1821
1822                        processPendingInstall(args, ret);
1823                        mHandler.sendEmptyMessage(MCS_UNBIND);
1824                    }
1825
1826                    break;
1827                }
1828                case START_INTENT_FILTER_VERIFICATIONS: {
1829                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1830                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1831                            params.replacing, params.pkg);
1832                    break;
1833                }
1834                case INTENT_FILTER_VERIFIED: {
1835                    final int verificationId = msg.arg1;
1836
1837                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1838                            verificationId);
1839                    if (state == null) {
1840                        Slog.w(TAG, "Invalid IntentFilter verification token "
1841                                + verificationId + " received");
1842                        break;
1843                    }
1844
1845                    final int userId = state.getUserId();
1846
1847                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1848                            "Processing IntentFilter verification with token:"
1849                            + verificationId + " and userId:" + userId);
1850
1851                    final IntentFilterVerificationResponse response =
1852                            (IntentFilterVerificationResponse) msg.obj;
1853
1854                    state.setVerifierResponse(response.callerUid, response.code);
1855
1856                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                            "IntentFilter verification with token:" + verificationId
1858                            + " and userId:" + userId
1859                            + " is settings verifier response with response code:"
1860                            + response.code);
1861
1862                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1863                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1864                                + response.getFailedDomainsString());
1865                    }
1866
1867                    if (state.isVerificationComplete()) {
1868                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1869                    } else {
1870                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1871                                "IntentFilter verification with token:" + verificationId
1872                                + " was not said to be complete");
1873                    }
1874
1875                    break;
1876                }
1877                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1878                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1879                            mInstantAppResolverConnection,
1880                            (InstantAppRequest) msg.obj,
1881                            mInstantAppInstallerActivity,
1882                            mHandler);
1883                }
1884            }
1885        }
1886    }
1887
1888    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1889        @Override
1890        public void onGidsChanged(int appId, int userId) {
1891            mHandler.post(new Runnable() {
1892                @Override
1893                public void run() {
1894                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1895                }
1896            });
1897        }
1898        @Override
1899        public void onPermissionGranted(int uid, int userId) {
1900            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1901
1902            // Not critical; if this is lost, the application has to request again.
1903            synchronized (mPackages) {
1904                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1905            }
1906        }
1907        @Override
1908        public void onInstallPermissionGranted() {
1909            synchronized (mPackages) {
1910                scheduleWriteSettingsLocked();
1911            }
1912        }
1913        @Override
1914        public void onPermissionRevoked(int uid, int userId) {
1915            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1916
1917            synchronized (mPackages) {
1918                // Critical; after this call the application should never have the permission
1919                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1920            }
1921
1922            final int appId = UserHandle.getAppId(uid);
1923            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1924        }
1925        @Override
1926        public void onInstallPermissionRevoked() {
1927            synchronized (mPackages) {
1928                scheduleWriteSettingsLocked();
1929            }
1930        }
1931        @Override
1932        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1933            synchronized (mPackages) {
1934                for (int userId : updatedUserIds) {
1935                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1936                }
1937            }
1938        }
1939        @Override
1940        public void onInstallPermissionUpdated() {
1941            synchronized (mPackages) {
1942                scheduleWriteSettingsLocked();
1943            }
1944        }
1945        @Override
1946        public void onPermissionRemoved() {
1947            synchronized (mPackages) {
1948                mSettings.writeLPr();
1949            }
1950        }
1951    };
1952
1953    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1954            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1955            boolean launchedForRestore, String installerPackage,
1956            IPackageInstallObserver2 installObserver) {
1957        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1958            // Send the removed broadcasts
1959            if (res.removedInfo != null) {
1960                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1961            }
1962
1963            // Now that we successfully installed the package, grant runtime
1964            // permissions if requested before broadcasting the install. Also
1965            // for legacy apps in permission review mode we clear the permission
1966            // review flag which is used to emulate runtime permissions for
1967            // legacy apps.
1968            if (grantPermissions) {
1969                final int callingUid = Binder.getCallingUid();
1970                mPermissionManager.grantRequestedRuntimePermissions(
1971                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1972                        mPermissionCallback);
1973            }
1974
1975            final boolean update = res.removedInfo != null
1976                    && res.removedInfo.removedPackage != null;
1977            final String installerPackageName =
1978                    res.installerPackageName != null
1979                            ? res.installerPackageName
1980                            : res.removedInfo != null
1981                                    ? res.removedInfo.installerPackageName
1982                                    : null;
1983
1984            // If this is the first time we have child packages for a disabled privileged
1985            // app that had no children, we grant requested runtime permissions to the new
1986            // children if the parent on the system image had them already granted.
1987            if (res.pkg.parentPackage != null) {
1988                final int callingUid = Binder.getCallingUid();
1989                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1990                        res.pkg, callingUid, mPermissionCallback);
1991            }
1992
1993            synchronized (mPackages) {
1994                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1995            }
1996
1997            final String packageName = res.pkg.applicationInfo.packageName;
1998
1999            // Determine the set of users who are adding this package for
2000            // the first time vs. those who are seeing an update.
2001            int[] firstUserIds = EMPTY_INT_ARRAY;
2002            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
2003            int[] updateUserIds = EMPTY_INT_ARRAY;
2004            int[] instantUserIds = EMPTY_INT_ARRAY;
2005            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2006            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2007            for (int newUser : res.newUsers) {
2008                final boolean isInstantApp = ps.getInstantApp(newUser);
2009                if (allNewUsers) {
2010                    if (isInstantApp) {
2011                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2012                    } else {
2013                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2014                    }
2015                    continue;
2016                }
2017                boolean isNew = true;
2018                for (int origUser : res.origUsers) {
2019                    if (origUser == newUser) {
2020                        isNew = false;
2021                        break;
2022                    }
2023                }
2024                if (isNew) {
2025                    if (isInstantApp) {
2026                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2027                    } else {
2028                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2029                    }
2030                } else {
2031                    if (isInstantApp) {
2032                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2033                    } else {
2034                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2035                    }
2036                }
2037            }
2038
2039            // Send installed broadcasts if the package is not a static shared lib.
2040            if (res.pkg.staticSharedLibName == null) {
2041                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2042
2043                // Send added for users that see the package for the first time
2044                // sendPackageAddedForNewUsers also deals with system apps
2045                int appId = UserHandle.getAppId(res.uid);
2046                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2047                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2048                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2049
2050                // Send added for users that don't see the package for the first time
2051                Bundle extras = new Bundle(1);
2052                extras.putInt(Intent.EXTRA_UID, res.uid);
2053                if (update) {
2054                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2055                }
2056                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2057                        extras, 0 /*flags*/,
2058                        null /*targetPackage*/, null /*finishedReceiver*/,
2059                        updateUserIds, instantUserIds);
2060                if (installerPackageName != null) {
2061                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2062                            extras, 0 /*flags*/,
2063                            installerPackageName, null /*finishedReceiver*/,
2064                            updateUserIds, instantUserIds);
2065                }
2066
2067                // Send replaced for users that don't see the package for the first time
2068                if (update) {
2069                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2070                            packageName, extras, 0 /*flags*/,
2071                            null /*targetPackage*/, null /*finishedReceiver*/,
2072                            updateUserIds, instantUserIds);
2073                    if (installerPackageName != null) {
2074                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2075                                extras, 0 /*flags*/,
2076                                installerPackageName, null /*finishedReceiver*/,
2077                                updateUserIds, instantUserIds);
2078                    }
2079                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2080                            null /*package*/, null /*extras*/, 0 /*flags*/,
2081                            packageName /*targetPackage*/,
2082                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2083                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2084                    // First-install and we did a restore, so we're responsible for the
2085                    // first-launch broadcast.
2086                    if (DEBUG_BACKUP) {
2087                        Slog.i(TAG, "Post-restore of " + packageName
2088                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2089                    }
2090                    sendFirstLaunchBroadcast(packageName, installerPackage,
2091                            firstUserIds, firstInstantUserIds);
2092                }
2093
2094                // Send broadcast package appeared if forward locked/external for all users
2095                // treat asec-hosted packages like removable media on upgrade
2096                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2097                    if (DEBUG_INSTALL) {
2098                        Slog.i(TAG, "upgrading pkg " + res.pkg
2099                                + " is ASEC-hosted -> AVAILABLE");
2100                    }
2101                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2102                    ArrayList<String> pkgList = new ArrayList<>(1);
2103                    pkgList.add(packageName);
2104                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2105                }
2106            }
2107
2108            // Work that needs to happen on first install within each user
2109            if (firstUserIds != null && firstUserIds.length > 0) {
2110                synchronized (mPackages) {
2111                    for (int userId : firstUserIds) {
2112                        // If this app is a browser and it's newly-installed for some
2113                        // users, clear any default-browser state in those users. The
2114                        // app's nature doesn't depend on the user, so we can just check
2115                        // its browser nature in any user and generalize.
2116                        if (packageIsBrowser(packageName, userId)) {
2117                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2118                        }
2119
2120                        // We may also need to apply pending (restored) runtime
2121                        // permission grants within these users.
2122                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2123                    }
2124                }
2125            }
2126
2127            if (allNewUsers && !update) {
2128                notifyPackageAdded(packageName);
2129            }
2130
2131            // Log current value of "unknown sources" setting
2132            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2133                    getUnknownSourcesSettings());
2134
2135            // Remove the replaced package's older resources safely now
2136            // We delete after a gc for applications  on sdcard.
2137            if (res.removedInfo != null && res.removedInfo.args != null) {
2138                Runtime.getRuntime().gc();
2139                synchronized (mInstallLock) {
2140                    res.removedInfo.args.doPostDeleteLI(true);
2141                }
2142            } else {
2143                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2144                // and not block here.
2145                VMRuntime.getRuntime().requestConcurrentGC();
2146            }
2147
2148            // Notify DexManager that the package was installed for new users.
2149            // The updated users should already be indexed and the package code paths
2150            // should not change.
2151            // Don't notify the manager for ephemeral apps as they are not expected to
2152            // survive long enough to benefit of background optimizations.
2153            for (int userId : firstUserIds) {
2154                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2155                // There's a race currently where some install events may interleave with an uninstall.
2156                // This can lead to package info being null (b/36642664).
2157                if (info != null) {
2158                    mDexManager.notifyPackageInstalled(info, userId);
2159                }
2160            }
2161        }
2162
2163        // If someone is watching installs - notify them
2164        if (installObserver != null) {
2165            try {
2166                Bundle extras = extrasForInstallResult(res);
2167                installObserver.onPackageInstalled(res.name, res.returnCode,
2168                        res.returnMsg, extras);
2169            } catch (RemoteException e) {
2170                Slog.i(TAG, "Observer no longer exists.");
2171            }
2172        }
2173    }
2174
2175    private StorageEventListener mStorageListener = new StorageEventListener() {
2176        @Override
2177        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2178            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2179                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2180                    final String volumeUuid = vol.getFsUuid();
2181
2182                    // Clean up any users or apps that were removed or recreated
2183                    // while this volume was missing
2184                    sUserManager.reconcileUsers(volumeUuid);
2185                    reconcileApps(volumeUuid);
2186
2187                    // Clean up any install sessions that expired or were
2188                    // cancelled while this volume was missing
2189                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2190
2191                    loadPrivatePackages(vol);
2192
2193                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2194                    unloadPrivatePackages(vol);
2195                }
2196            }
2197        }
2198
2199        @Override
2200        public void onVolumeForgotten(String fsUuid) {
2201            if (TextUtils.isEmpty(fsUuid)) {
2202                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2203                return;
2204            }
2205
2206            // Remove any apps installed on the forgotten volume
2207            synchronized (mPackages) {
2208                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2209                for (PackageSetting ps : packages) {
2210                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2211                    deletePackageVersioned(new VersionedPackage(ps.name,
2212                            PackageManager.VERSION_CODE_HIGHEST),
2213                            new LegacyPackageDeleteObserver(null).getBinder(),
2214                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2215                    // Try very hard to release any references to this package
2216                    // so we don't risk the system server being killed due to
2217                    // open FDs
2218                    AttributeCache.instance().removePackage(ps.name);
2219                }
2220
2221                mSettings.onVolumeForgotten(fsUuid);
2222                mSettings.writeLPr();
2223            }
2224        }
2225    };
2226
2227    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2228        Bundle extras = null;
2229        switch (res.returnCode) {
2230            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2231                extras = new Bundle();
2232                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2233                        res.origPermission);
2234                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2235                        res.origPackage);
2236                break;
2237            }
2238            case PackageManager.INSTALL_SUCCEEDED: {
2239                extras = new Bundle();
2240                extras.putBoolean(Intent.EXTRA_REPLACING,
2241                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2242                break;
2243            }
2244        }
2245        return extras;
2246    }
2247
2248    void scheduleWriteSettingsLocked() {
2249        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2250            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2251        }
2252    }
2253
2254    void scheduleWritePackageListLocked(int userId) {
2255        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2256            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2257            msg.arg1 = userId;
2258            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2259        }
2260    }
2261
2262    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2263        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2264        scheduleWritePackageRestrictionsLocked(userId);
2265    }
2266
2267    void scheduleWritePackageRestrictionsLocked(int userId) {
2268        final int[] userIds = (userId == UserHandle.USER_ALL)
2269                ? sUserManager.getUserIds() : new int[]{userId};
2270        for (int nextUserId : userIds) {
2271            if (!sUserManager.exists(nextUserId)) return;
2272            mDirtyUsers.add(nextUserId);
2273            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2274                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2275            }
2276        }
2277    }
2278
2279    public static PackageManagerService main(Context context, Installer installer,
2280            boolean factoryTest, boolean onlyCore) {
2281        // Self-check for initial settings.
2282        PackageManagerServiceCompilerMapping.checkProperties();
2283
2284        PackageManagerService m = new PackageManagerService(context, installer,
2285                factoryTest, onlyCore);
2286        m.enableSystemUserPackages();
2287        ServiceManager.addService("package", m);
2288        final PackageManagerNative pmn = m.new PackageManagerNative();
2289        ServiceManager.addService("package_native", pmn);
2290        return m;
2291    }
2292
2293    private void enableSystemUserPackages() {
2294        if (!UserManager.isSplitSystemUser()) {
2295            return;
2296        }
2297        // For system user, enable apps based on the following conditions:
2298        // - app is whitelisted or belong to one of these groups:
2299        //   -- system app which has no launcher icons
2300        //   -- system app which has INTERACT_ACROSS_USERS permission
2301        //   -- system IME app
2302        // - app is not in the blacklist
2303        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2304        Set<String> enableApps = new ArraySet<>();
2305        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2306                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2307                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2308        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2309        enableApps.addAll(wlApps);
2310        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2311                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2312        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2313        enableApps.removeAll(blApps);
2314        Log.i(TAG, "Applications installed for system user: " + enableApps);
2315        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2316                UserHandle.SYSTEM);
2317        final int allAppsSize = allAps.size();
2318        synchronized (mPackages) {
2319            for (int i = 0; i < allAppsSize; i++) {
2320                String pName = allAps.get(i);
2321                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2322                // Should not happen, but we shouldn't be failing if it does
2323                if (pkgSetting == null) {
2324                    continue;
2325                }
2326                boolean install = enableApps.contains(pName);
2327                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2328                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2329                            + " for system user");
2330                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2331                }
2332            }
2333            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2334        }
2335    }
2336
2337    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2338        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2339                Context.DISPLAY_SERVICE);
2340        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2341    }
2342
2343    /**
2344     * Requests that files preopted on a secondary system partition be copied to the data partition
2345     * if possible.  Note that the actual copying of the files is accomplished by init for security
2346     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2347     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2348     */
2349    private static void requestCopyPreoptedFiles() {
2350        final int WAIT_TIME_MS = 100;
2351        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2352        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2353            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2354            // We will wait for up to 100 seconds.
2355            final long timeStart = SystemClock.uptimeMillis();
2356            final long timeEnd = timeStart + 100 * 1000;
2357            long timeNow = timeStart;
2358            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2359                try {
2360                    Thread.sleep(WAIT_TIME_MS);
2361                } catch (InterruptedException e) {
2362                    // Do nothing
2363                }
2364                timeNow = SystemClock.uptimeMillis();
2365                if (timeNow > timeEnd) {
2366                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2367                    Slog.wtf(TAG, "cppreopt did not finish!");
2368                    break;
2369                }
2370            }
2371
2372            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2373        }
2374    }
2375
2376    public PackageManagerService(Context context, Installer installer,
2377            boolean factoryTest, boolean onlyCore) {
2378        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2379        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2380        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2381                SystemClock.uptimeMillis());
2382
2383        if (mSdkVersion <= 0) {
2384            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2385        }
2386
2387        mContext = context;
2388
2389        mFactoryTest = factoryTest;
2390        mOnlyCore = onlyCore;
2391        mMetrics = new DisplayMetrics();
2392        mInstaller = installer;
2393
2394        // Create sub-components that provide services / data. Order here is important.
2395        synchronized (mInstallLock) {
2396        synchronized (mPackages) {
2397            // Expose private service for system components to use.
2398            LocalServices.addService(
2399                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2400            sUserManager = new UserManagerService(context, this,
2401                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2402            mPermissionManager = PermissionManagerService.create(context,
2403                    new DefaultPermissionGrantedCallback() {
2404                        @Override
2405                        public void onDefaultRuntimePermissionsGranted(int userId) {
2406                            synchronized(mPackages) {
2407                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2408                            }
2409                        }
2410                    }, mPackages /*externalLock*/);
2411            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2412            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2413        }
2414        }
2415        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2416                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2417        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2418                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2419        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429
2430        String separateProcesses = SystemProperties.get("debug.separate_processes");
2431        if (separateProcesses != null && separateProcesses.length() > 0) {
2432            if ("*".equals(separateProcesses)) {
2433                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2434                mSeparateProcesses = null;
2435                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2436            } else {
2437                mDefParseFlags = 0;
2438                mSeparateProcesses = separateProcesses.split(",");
2439                Slog.w(TAG, "Running with debug.separate_processes: "
2440                        + separateProcesses);
2441            }
2442        } else {
2443            mDefParseFlags = 0;
2444            mSeparateProcesses = null;
2445        }
2446
2447        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2448                "*dexopt*");
2449        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2450                installer, mInstallLock);
2451        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2452                dexManagerListener);
2453        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2454        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2455
2456        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2457                FgThread.get().getLooper());
2458
2459        getDefaultDisplayMetrics(context, mMetrics);
2460
2461        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2462        SystemConfig systemConfig = SystemConfig.getInstance();
2463        mAvailableFeatures = systemConfig.getAvailableFeatures();
2464        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2465
2466        mProtectedPackages = new ProtectedPackages(mContext);
2467
2468        synchronized (mInstallLock) {
2469        // writer
2470        synchronized (mPackages) {
2471            mHandlerThread = new ServiceThread(TAG,
2472                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2473            mHandlerThread.start();
2474            mHandler = new PackageHandler(mHandlerThread.getLooper());
2475            mProcessLoggingHandler = new ProcessLoggingHandler();
2476            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2477            mInstantAppRegistry = new InstantAppRegistry(this);
2478
2479            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2480            final int builtInLibCount = libConfig.size();
2481            for (int i = 0; i < builtInLibCount; i++) {
2482                String name = libConfig.keyAt(i);
2483                String path = libConfig.valueAt(i);
2484                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2485                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2486            }
2487
2488            SELinuxMMAC.readInstallPolicy();
2489
2490            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2491            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2492            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2493
2494            // Clean up orphaned packages for which the code path doesn't exist
2495            // and they are an update to a system app - caused by bug/32321269
2496            final int packageSettingCount = mSettings.mPackages.size();
2497            for (int i = packageSettingCount - 1; i >= 0; i--) {
2498                PackageSetting ps = mSettings.mPackages.valueAt(i);
2499                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2500                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2501                    mSettings.mPackages.removeAt(i);
2502                    mSettings.enableSystemPackageLPw(ps.name);
2503                }
2504            }
2505
2506            if (mFirstBoot) {
2507                requestCopyPreoptedFiles();
2508            }
2509
2510            String customResolverActivity = Resources.getSystem().getString(
2511                    R.string.config_customResolverActivity);
2512            if (TextUtils.isEmpty(customResolverActivity)) {
2513                customResolverActivity = null;
2514            } else {
2515                mCustomResolverComponentName = ComponentName.unflattenFromString(
2516                        customResolverActivity);
2517            }
2518
2519            long startTime = SystemClock.uptimeMillis();
2520
2521            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2522                    startTime);
2523
2524            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2525            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2526
2527            if (bootClassPath == null) {
2528                Slog.w(TAG, "No BOOTCLASSPATH found!");
2529            }
2530
2531            if (systemServerClassPath == null) {
2532                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2533            }
2534
2535            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2536
2537            final VersionInfo ver = mSettings.getInternalVersion();
2538            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2539            if (mIsUpgrade) {
2540                logCriticalInfo(Log.INFO,
2541                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2542            }
2543
2544            // when upgrading from pre-M, promote system app permissions from install to runtime
2545            mPromoteSystemApps =
2546                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2547
2548            // When upgrading from pre-N, we need to handle package extraction like first boot,
2549            // as there is no profiling data available.
2550            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2551
2552            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2553
2554            // save off the names of pre-existing system packages prior to scanning; we don't
2555            // want to automatically grant runtime permissions for new system apps
2556            if (mPromoteSystemApps) {
2557                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2558                while (pkgSettingIter.hasNext()) {
2559                    PackageSetting ps = pkgSettingIter.next();
2560                    if (isSystemApp(ps)) {
2561                        mExistingSystemPackages.add(ps.name);
2562                    }
2563                }
2564            }
2565
2566            mCacheDir = preparePackageParserCache(mIsUpgrade);
2567
2568            // Set flag to monitor and not change apk file paths when
2569            // scanning install directories.
2570            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2571
2572            if (mIsUpgrade || mFirstBoot) {
2573                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2574            }
2575
2576            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2577            // For security and version matching reason, only consider
2578            // overlay packages if they reside in the right directory.
2579            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2580                    mDefParseFlags
2581                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2582                    scanFlags
2583                    | SCAN_AS_SYSTEM
2584                    | SCAN_AS_VENDOR,
2585                    0);
2586            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2587                    mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2589                    scanFlags
2590                    | SCAN_AS_SYSTEM
2591                    | SCAN_AS_PRODUCT,
2592                    0);
2593
2594            mParallelPackageParserCallback.findStaticOverlayPackages();
2595
2596            // Find base frameworks (resource packages without code).
2597            scanDirTracedLI(frameworkDir,
2598                    mDefParseFlags
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2600                    scanFlags
2601                    | SCAN_NO_DEX
2602                    | SCAN_AS_SYSTEM
2603                    | SCAN_AS_PRIVILEGED,
2604                    0);
2605
2606            // Collect privileged system packages.
2607            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2608            scanDirTracedLI(privilegedAppDir,
2609                    mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2611                    scanFlags
2612                    | SCAN_AS_SYSTEM
2613                    | SCAN_AS_PRIVILEGED,
2614                    0);
2615
2616            // Collect ordinary system packages.
2617            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2618            scanDirTracedLI(systemAppDir,
2619                    mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2621                    scanFlags
2622                    | SCAN_AS_SYSTEM,
2623                    0);
2624
2625            // Collect privileged vendor packages.
2626            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2627            try {
2628                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2629            } catch (IOException e) {
2630                // failed to look up canonical path, continue with original one
2631            }
2632            scanDirTracedLI(privilegedVendorAppDir,
2633                    mDefParseFlags
2634                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2635                    scanFlags
2636                    | SCAN_AS_SYSTEM
2637                    | SCAN_AS_VENDOR
2638                    | SCAN_AS_PRIVILEGED,
2639                    0);
2640
2641            // Collect ordinary vendor packages.
2642            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2643            try {
2644                vendorAppDir = vendorAppDir.getCanonicalFile();
2645            } catch (IOException e) {
2646                // failed to look up canonical path, continue with original one
2647            }
2648            scanDirTracedLI(vendorAppDir,
2649                    mDefParseFlags
2650                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2651                    scanFlags
2652                    | SCAN_AS_SYSTEM
2653                    | SCAN_AS_VENDOR,
2654                    0);
2655
2656            // Collect privileged odm packages. /odm is another vendor partition
2657            // other than /vendor.
2658            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2659                        "priv-app");
2660            try {
2661                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2662            } catch (IOException e) {
2663                // failed to look up canonical path, continue with original one
2664            }
2665            scanDirTracedLI(privilegedOdmAppDir,
2666                    mDefParseFlags
2667                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2668                    scanFlags
2669                    | SCAN_AS_SYSTEM
2670                    | SCAN_AS_VENDOR
2671                    | SCAN_AS_PRIVILEGED,
2672                    0);
2673
2674            // Collect ordinary odm packages. /odm is another vendor partition
2675            // other than /vendor.
2676            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2677            try {
2678                odmAppDir = odmAppDir.getCanonicalFile();
2679            } catch (IOException e) {
2680                // failed to look up canonical path, continue with original one
2681            }
2682            scanDirTracedLI(odmAppDir,
2683                    mDefParseFlags
2684                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2685                    scanFlags
2686                    | SCAN_AS_SYSTEM
2687                    | SCAN_AS_VENDOR,
2688                    0);
2689
2690            // Collect all OEM packages.
2691            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2692            scanDirTracedLI(oemAppDir,
2693                    mDefParseFlags
2694                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2695                    scanFlags
2696                    | SCAN_AS_SYSTEM
2697                    | SCAN_AS_OEM,
2698                    0);
2699
2700            // Collected privileged product packages.
2701            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2702            try {
2703                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2704            } catch (IOException e) {
2705                // failed to look up canonical path, continue with original one
2706            }
2707            scanDirTracedLI(privilegedProductAppDir,
2708                    mDefParseFlags
2709                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2710                    scanFlags
2711                    | SCAN_AS_SYSTEM
2712                    | SCAN_AS_PRODUCT
2713                    | SCAN_AS_PRIVILEGED,
2714                    0);
2715
2716            // Collect ordinary product packages.
2717            File productAppDir = new File(Environment.getProductDirectory(), "app");
2718            try {
2719                productAppDir = productAppDir.getCanonicalFile();
2720            } catch (IOException e) {
2721                // failed to look up canonical path, continue with original one
2722            }
2723            scanDirTracedLI(productAppDir,
2724                    mDefParseFlags
2725                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2726                    scanFlags
2727                    | SCAN_AS_SYSTEM
2728                    | SCAN_AS_PRODUCT,
2729                    0);
2730
2731            // Prune any system packages that no longer exist.
2732            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2733            // Stub packages must either be replaced with full versions in the /data
2734            // partition or be disabled.
2735            final List<String> stubSystemApps = new ArrayList<>();
2736            if (!mOnlyCore) {
2737                // do this first before mucking with mPackages for the "expecting better" case
2738                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2739                while (pkgIterator.hasNext()) {
2740                    final PackageParser.Package pkg = pkgIterator.next();
2741                    if (pkg.isStub) {
2742                        stubSystemApps.add(pkg.packageName);
2743                    }
2744                }
2745
2746                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2747                while (psit.hasNext()) {
2748                    PackageSetting ps = psit.next();
2749
2750                    /*
2751                     * If this is not a system app, it can't be a
2752                     * disable system app.
2753                     */
2754                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2755                        continue;
2756                    }
2757
2758                    /*
2759                     * If the package is scanned, it's not erased.
2760                     */
2761                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2762                    if (scannedPkg != null) {
2763                        /*
2764                         * If the system app is both scanned and in the
2765                         * disabled packages list, then it must have been
2766                         * added via OTA. Remove it from the currently
2767                         * scanned package so the previously user-installed
2768                         * application can be scanned.
2769                         */
2770                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2771                            logCriticalInfo(Log.WARN,
2772                                    "Expecting better updated system app for " + ps.name
2773                                    + "; removing system app.  Last known"
2774                                    + " codePath=" + ps.codePathString
2775                                    + ", versionCode=" + ps.versionCode
2776                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2777                            removePackageLI(scannedPkg, true);
2778                            mExpectingBetter.put(ps.name, ps.codePath);
2779                        }
2780
2781                        continue;
2782                    }
2783
2784                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2785                        psit.remove();
2786                        logCriticalInfo(Log.WARN, "System package " + ps.name
2787                                + " no longer exists; it's data will be wiped");
2788                        // Actual deletion of code and data will be handled by later
2789                        // reconciliation step
2790                    } else {
2791                        // we still have a disabled system package, but, it still might have
2792                        // been removed. check the code path still exists and check there's
2793                        // still a package. the latter can happen if an OTA keeps the same
2794                        // code path, but, changes the package name.
2795                        final PackageSetting disabledPs =
2796                                mSettings.getDisabledSystemPkgLPr(ps.name);
2797                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2798                                || disabledPs.pkg == null) {
2799                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2800                        }
2801                    }
2802                }
2803            }
2804
2805            //delete tmp files
2806            deleteTempPackageFiles();
2807
2808            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2809
2810            // Remove any shared userIDs that have no associated packages
2811            mSettings.pruneSharedUsersLPw();
2812            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2813            final int systemPackagesCount = mPackages.size();
2814            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2815                    + " ms, packageCount: " + systemPackagesCount
2816                    + " , timePerPackage: "
2817                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2818                    + " , cached: " + cachedSystemApps);
2819            if (mIsUpgrade && systemPackagesCount > 0) {
2820                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2821                        ((int) systemScanTime) / systemPackagesCount);
2822            }
2823            if (!mOnlyCore) {
2824                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2825                        SystemClock.uptimeMillis());
2826                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2827
2828                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2829                        | PackageParser.PARSE_FORWARD_LOCK,
2830                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2831
2832                // Remove disable package settings for updated system apps that were
2833                // removed via an OTA. If the update is no longer present, remove the
2834                // app completely. Otherwise, revoke their system privileges.
2835                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2836                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2837                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2838                    final String msg;
2839                    if (deletedPkg == null) {
2840                        // should have found an update, but, we didn't; remove everything
2841                        msg = "Updated system package " + deletedAppName
2842                                + " no longer exists; removing its data";
2843                        // Actual deletion of code and data will be handled by later
2844                        // reconciliation step
2845                    } else {
2846                        // found an update; revoke system privileges
2847                        msg = "Updated system package + " + deletedAppName
2848                                + " no longer exists; revoking system privileges";
2849
2850                        // Don't do anything if a stub is removed from the system image. If
2851                        // we were to remove the uncompressed version from the /data partition,
2852                        // this is where it'd be done.
2853
2854                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2855                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2856                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2857                    }
2858                    logCriticalInfo(Log.WARN, msg);
2859                }
2860
2861                /*
2862                 * Make sure all system apps that we expected to appear on
2863                 * the userdata partition actually showed up. If they never
2864                 * appeared, crawl back and revive the system version.
2865                 */
2866                for (int i = 0; i < mExpectingBetter.size(); i++) {
2867                    final String packageName = mExpectingBetter.keyAt(i);
2868                    if (!mPackages.containsKey(packageName)) {
2869                        final File scanFile = mExpectingBetter.valueAt(i);
2870
2871                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2872                                + " but never showed up; reverting to system");
2873
2874                        final @ParseFlags int reparseFlags;
2875                        final @ScanFlags int rescanFlags;
2876                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2877                            reparseFlags =
2878                                    mDefParseFlags |
2879                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2880                            rescanFlags =
2881                                    scanFlags
2882                                    | SCAN_AS_SYSTEM
2883                                    | SCAN_AS_PRIVILEGED;
2884                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2885                            reparseFlags =
2886                                    mDefParseFlags |
2887                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2888                            rescanFlags =
2889                                    scanFlags
2890                                    | SCAN_AS_SYSTEM;
2891                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2892                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2893                            reparseFlags =
2894                                    mDefParseFlags |
2895                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2896                            rescanFlags =
2897                                    scanFlags
2898                                    | SCAN_AS_SYSTEM
2899                                    | SCAN_AS_VENDOR
2900                                    | SCAN_AS_PRIVILEGED;
2901                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2902                                || FileUtils.contains(odmAppDir, scanFile)) {
2903                            reparseFlags =
2904                                    mDefParseFlags |
2905                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2906                            rescanFlags =
2907                                    scanFlags
2908                                    | SCAN_AS_SYSTEM
2909                                    | SCAN_AS_VENDOR;
2910                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2911                            reparseFlags =
2912                                    mDefParseFlags |
2913                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2914                            rescanFlags =
2915                                    scanFlags
2916                                    | SCAN_AS_SYSTEM
2917                                    | SCAN_AS_OEM;
2918                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2919                            reparseFlags =
2920                                    mDefParseFlags |
2921                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2922                            rescanFlags =
2923                                    scanFlags
2924                                    | SCAN_AS_SYSTEM
2925                                    | SCAN_AS_PRODUCT
2926                                    | SCAN_AS_PRIVILEGED;
2927                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2928                            reparseFlags =
2929                                    mDefParseFlags |
2930                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2931                            rescanFlags =
2932                                    scanFlags
2933                                    | SCAN_AS_SYSTEM
2934                                    | SCAN_AS_PRODUCT;
2935                        } else {
2936                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2937                            continue;
2938                        }
2939
2940                        mSettings.enableSystemPackageLPw(packageName);
2941
2942                        try {
2943                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2944                        } catch (PackageManagerException e) {
2945                            Slog.e(TAG, "Failed to parse original system package: "
2946                                    + e.getMessage());
2947                        }
2948                    }
2949                }
2950
2951                // Uncompress and install any stubbed system applications.
2952                // This must be done last to ensure all stubs are replaced or disabled.
2953                decompressSystemApplications(stubSystemApps, scanFlags);
2954
2955                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2956                                - cachedSystemApps;
2957
2958                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2959                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2960                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2961                        + " ms, packageCount: " + dataPackagesCount
2962                        + " , timePerPackage: "
2963                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2964                        + " , cached: " + cachedNonSystemApps);
2965                if (mIsUpgrade && dataPackagesCount > 0) {
2966                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2967                            ((int) dataScanTime) / dataPackagesCount);
2968                }
2969            }
2970            mExpectingBetter.clear();
2971
2972            // Resolve the storage manager.
2973            mStorageManagerPackage = getStorageManagerPackageName();
2974
2975            // Resolve protected action filters. Only the setup wizard is allowed to
2976            // have a high priority filter for these actions.
2977            mSetupWizardPackage = getSetupWizardPackageName();
2978            if (mProtectedFilters.size() > 0) {
2979                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2980                    Slog.i(TAG, "No setup wizard;"
2981                        + " All protected intents capped to priority 0");
2982                }
2983                for (ActivityIntentInfo filter : mProtectedFilters) {
2984                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2985                        if (DEBUG_FILTERS) {
2986                            Slog.i(TAG, "Found setup wizard;"
2987                                + " allow priority " + filter.getPriority() + ";"
2988                                + " package: " + filter.activity.info.packageName
2989                                + " activity: " + filter.activity.className
2990                                + " priority: " + filter.getPriority());
2991                        }
2992                        // skip setup wizard; allow it to keep the high priority filter
2993                        continue;
2994                    }
2995                    if (DEBUG_FILTERS) {
2996                        Slog.i(TAG, "Protected action; cap priority to 0;"
2997                                + " package: " + filter.activity.info.packageName
2998                                + " activity: " + filter.activity.className
2999                                + " origPrio: " + filter.getPriority());
3000                    }
3001                    filter.setPriority(0);
3002                }
3003            }
3004
3005            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3006
3007            mDeferProtectedFilters = false;
3008            mProtectedFilters.clear();
3009
3010            // Now that we know all of the shared libraries, update all clients to have
3011            // the correct library paths.
3012            updateAllSharedLibrariesLPw(null);
3013
3014            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3015                // NOTE: We ignore potential failures here during a system scan (like
3016                // the rest of the commands above) because there's precious little we
3017                // can do about it. A settings error is reported, though.
3018                final List<String> changedAbiCodePath =
3019                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3020                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3021                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3022                        final String codePathString = changedAbiCodePath.get(i);
3023                        try {
3024                            mInstaller.rmdex(codePathString,
3025                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3026                        } catch (InstallerException ignored) {
3027                        }
3028                    }
3029                }
3030                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3031                // SELinux domain.
3032                setting.fixSeInfoLocked();
3033            }
3034
3035            // Now that we know all the packages we are keeping,
3036            // read and update their last usage times.
3037            mPackageUsage.read(mPackages);
3038            mCompilerStats.read();
3039
3040            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3041                    SystemClock.uptimeMillis());
3042            Slog.i(TAG, "Time to scan packages: "
3043                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3044                    + " seconds");
3045
3046            // If the platform SDK has changed since the last time we booted,
3047            // we need to re-grant app permission to catch any new ones that
3048            // appear.  This is really a hack, and means that apps can in some
3049            // cases get permissions that the user didn't initially explicitly
3050            // allow...  it would be nice to have some better way to handle
3051            // this situation.
3052            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3053            if (sdkUpdated) {
3054                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3055                        + mSdkVersion + "; regranting permissions for internal storage");
3056            }
3057            mPermissionManager.updateAllPermissions(
3058                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3059                    mPermissionCallback);
3060            ver.sdkVersion = mSdkVersion;
3061
3062            // If this is the first boot or an update from pre-M, and it is a normal
3063            // boot, then we need to initialize the default preferred apps across
3064            // all defined users.
3065            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3066                for (UserInfo user : sUserManager.getUsers(true)) {
3067                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3068                    applyFactoryDefaultBrowserLPw(user.id);
3069                    primeDomainVerificationsLPw(user.id);
3070                }
3071            }
3072
3073            // Prepare storage for system user really early during boot,
3074            // since core system apps like SettingsProvider and SystemUI
3075            // can't wait for user to start
3076            final int storageFlags;
3077            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3078                storageFlags = StorageManager.FLAG_STORAGE_DE;
3079            } else {
3080                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3081            }
3082            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3083                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3084                    true /* onlyCoreApps */);
3085            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3086                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3087                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3088                traceLog.traceBegin("AppDataFixup");
3089                try {
3090                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3091                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3092                } catch (InstallerException e) {
3093                    Slog.w(TAG, "Trouble fixing GIDs", e);
3094                }
3095                traceLog.traceEnd();
3096
3097                traceLog.traceBegin("AppDataPrepare");
3098                if (deferPackages == null || deferPackages.isEmpty()) {
3099                    return;
3100                }
3101                int count = 0;
3102                for (String pkgName : deferPackages) {
3103                    PackageParser.Package pkg = null;
3104                    synchronized (mPackages) {
3105                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3106                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3107                            pkg = ps.pkg;
3108                        }
3109                    }
3110                    if (pkg != null) {
3111                        synchronized (mInstallLock) {
3112                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3113                                    true /* maybeMigrateAppData */);
3114                        }
3115                        count++;
3116                    }
3117                }
3118                traceLog.traceEnd();
3119                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3120            }, "prepareAppData");
3121
3122            // If this is first boot after an OTA, and a normal boot, then
3123            // we need to clear code cache directories.
3124            // Note that we do *not* clear the application profiles. These remain valid
3125            // across OTAs and are used to drive profile verification (post OTA) and
3126            // profile compilation (without waiting to collect a fresh set of profiles).
3127            if (mIsUpgrade && !onlyCore) {
3128                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3129                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3130                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3131                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3132                        // No apps are running this early, so no need to freeze
3133                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3134                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3135                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3136                    }
3137                }
3138                ver.fingerprint = Build.FINGERPRINT;
3139            }
3140
3141            checkDefaultBrowser();
3142
3143            // clear only after permissions and other defaults have been updated
3144            mExistingSystemPackages.clear();
3145            mPromoteSystemApps = false;
3146
3147            // All the changes are done during package scanning.
3148            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3149
3150            // can downgrade to reader
3151            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3152            mSettings.writeLPr();
3153            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3154            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3155                    SystemClock.uptimeMillis());
3156
3157            if (!mOnlyCore) {
3158                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3159                mRequiredInstallerPackage = getRequiredInstallerLPr();
3160                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3161                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3162                if (mIntentFilterVerifierComponent != null) {
3163                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3164                            mIntentFilterVerifierComponent);
3165                } else {
3166                    mIntentFilterVerifier = null;
3167                }
3168                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3169                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3170                        SharedLibraryInfo.VERSION_UNDEFINED);
3171                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3172                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3173                        SharedLibraryInfo.VERSION_UNDEFINED);
3174            } else {
3175                mRequiredVerifierPackage = null;
3176                mRequiredInstallerPackage = null;
3177                mRequiredUninstallerPackage = null;
3178                mIntentFilterVerifierComponent = null;
3179                mIntentFilterVerifier = null;
3180                mServicesSystemSharedLibraryPackageName = null;
3181                mSharedSystemSharedLibraryPackageName = null;
3182            }
3183
3184            mInstallerService = new PackageInstallerService(context, this);
3185            final Pair<ComponentName, String> instantAppResolverComponent =
3186                    getInstantAppResolverLPr();
3187            if (instantAppResolverComponent != null) {
3188                if (DEBUG_INSTANT) {
3189                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3190                }
3191                mInstantAppResolverConnection = new InstantAppResolverConnection(
3192                        mContext, instantAppResolverComponent.first,
3193                        instantAppResolverComponent.second);
3194                mInstantAppResolverSettingsComponent =
3195                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3196            } else {
3197                mInstantAppResolverConnection = null;
3198                mInstantAppResolverSettingsComponent = null;
3199            }
3200            updateInstantAppInstallerLocked(null);
3201
3202            // Read and update the usage of dex files.
3203            // Do this at the end of PM init so that all the packages have their
3204            // data directory reconciled.
3205            // At this point we know the code paths of the packages, so we can validate
3206            // the disk file and build the internal cache.
3207            // The usage file is expected to be small so loading and verifying it
3208            // should take a fairly small time compare to the other activities (e.g. package
3209            // scanning).
3210            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3211            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3212            for (int userId : currentUserIds) {
3213                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3214            }
3215            mDexManager.load(userPackages);
3216            if (mIsUpgrade) {
3217                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3218                        (int) (SystemClock.uptimeMillis() - startTime));
3219            }
3220        } // synchronized (mPackages)
3221        } // synchronized (mInstallLock)
3222
3223        // Now after opening every single application zip, make sure they
3224        // are all flushed.  Not really needed, but keeps things nice and
3225        // tidy.
3226        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3227        Runtime.getRuntime().gc();
3228        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3229
3230        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3231        FallbackCategoryProvider.loadFallbacks();
3232        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3233
3234        // The initial scanning above does many calls into installd while
3235        // holding the mPackages lock, but we're mostly interested in yelling
3236        // once we have a booted system.
3237        mInstaller.setWarnIfHeld(mPackages);
3238
3239        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3240    }
3241
3242    /**
3243     * Uncompress and install stub applications.
3244     * <p>In order to save space on the system partition, some applications are shipped in a
3245     * compressed form. In addition the compressed bits for the full application, the
3246     * system image contains a tiny stub comprised of only the Android manifest.
3247     * <p>During the first boot, attempt to uncompress and install the full application. If
3248     * the application can't be installed for any reason, disable the stub and prevent
3249     * uncompressing the full application during future boots.
3250     * <p>In order to forcefully attempt an installation of a full application, go to app
3251     * settings and enable the application.
3252     */
3253    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3254        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3255            final String pkgName = stubSystemApps.get(i);
3256            // skip if the system package is already disabled
3257            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3258                stubSystemApps.remove(i);
3259                continue;
3260            }
3261            // skip if the package isn't installed (?!); this should never happen
3262            final PackageParser.Package pkg = mPackages.get(pkgName);
3263            if (pkg == null) {
3264                stubSystemApps.remove(i);
3265                continue;
3266            }
3267            // skip if the package has been disabled by the user
3268            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3269            if (ps != null) {
3270                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3271                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3272                    stubSystemApps.remove(i);
3273                    continue;
3274                }
3275            }
3276
3277            if (DEBUG_COMPRESSION) {
3278                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3279            }
3280
3281            // uncompress the binary to its eventual destination on /data
3282            final File scanFile = decompressPackage(pkg);
3283            if (scanFile == null) {
3284                continue;
3285            }
3286
3287            // install the package to replace the stub on /system
3288            try {
3289                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3290                removePackageLI(pkg, true /*chatty*/);
3291                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3292                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3293                        UserHandle.USER_SYSTEM, "android");
3294                stubSystemApps.remove(i);
3295                continue;
3296            } catch (PackageManagerException e) {
3297                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3298            }
3299
3300            // any failed attempt to install the package will be cleaned up later
3301        }
3302
3303        // disable any stub still left; these failed to install the full application
3304        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3305            final String pkgName = stubSystemApps.get(i);
3306            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3307            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3308                    UserHandle.USER_SYSTEM, "android");
3309            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3310        }
3311    }
3312
3313    /**
3314     * Decompresses the given package on the system image onto
3315     * the /data partition.
3316     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3317     */
3318    private File decompressPackage(PackageParser.Package pkg) {
3319        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3320        if (compressedFiles == null || compressedFiles.length == 0) {
3321            if (DEBUG_COMPRESSION) {
3322                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3323            }
3324            return null;
3325        }
3326        final File dstCodePath =
3327                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3328        int ret = PackageManager.INSTALL_SUCCEEDED;
3329        try {
3330            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3331            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3332            for (File srcFile : compressedFiles) {
3333                final String srcFileName = srcFile.getName();
3334                final String dstFileName = srcFileName.substring(
3335                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3336                final File dstFile = new File(dstCodePath, dstFileName);
3337                ret = decompressFile(srcFile, dstFile);
3338                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3339                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3340                            + "; pkg: " + pkg.packageName
3341                            + ", file: " + dstFileName);
3342                    break;
3343                }
3344            }
3345        } catch (ErrnoException e) {
3346            logCriticalInfo(Log.ERROR, "Failed to decompress"
3347                    + "; pkg: " + pkg.packageName
3348                    + ", err: " + e.errno);
3349        }
3350        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3351            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3352            NativeLibraryHelper.Handle handle = null;
3353            try {
3354                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3355                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3356                        null /*abiOverride*/);
3357            } catch (IOException e) {
3358                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3359                        + "; pkg: " + pkg.packageName);
3360                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3361            } finally {
3362                IoUtils.closeQuietly(handle);
3363            }
3364        }
3365        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3366            if (dstCodePath == null || !dstCodePath.exists()) {
3367                return null;
3368            }
3369            removeCodePathLI(dstCodePath);
3370            return null;
3371        }
3372
3373        return dstCodePath;
3374    }
3375
3376    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3377        // we're only interested in updating the installer appliction when 1) it's not
3378        // already set or 2) the modified package is the installer
3379        if (mInstantAppInstallerActivity != null
3380                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3381                        .equals(modifiedPackage)) {
3382            return;
3383        }
3384        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3385    }
3386
3387    private static File preparePackageParserCache(boolean isUpgrade) {
3388        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3389            return null;
3390        }
3391
3392        // Disable package parsing on eng builds to allow for faster incremental development.
3393        if (Build.IS_ENG) {
3394            return null;
3395        }
3396
3397        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3398            Slog.i(TAG, "Disabling package parser cache due to system property.");
3399            return null;
3400        }
3401
3402        // The base directory for the package parser cache lives under /data/system/.
3403        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3404                "package_cache");
3405        if (cacheBaseDir == null) {
3406            return null;
3407        }
3408
3409        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3410        // This also serves to "GC" unused entries when the package cache version changes (which
3411        // can only happen during upgrades).
3412        if (isUpgrade) {
3413            FileUtils.deleteContents(cacheBaseDir);
3414        }
3415
3416
3417        // Return the versioned package cache directory. This is something like
3418        // "/data/system/package_cache/1"
3419        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3420
3421        if (cacheDir == null) {
3422            // Something went wrong. Attempt to delete everything and return.
3423            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3424            FileUtils.deleteContentsAndDir(cacheBaseDir);
3425            return null;
3426        }
3427
3428        // The following is a workaround to aid development on non-numbered userdebug
3429        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3430        // the system partition is newer.
3431        //
3432        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3433        // that starts with "eng." to signify that this is an engineering build and not
3434        // destined for release.
3435        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3436            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3437
3438            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3439            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3440            // in general and should not be used for production changes. In this specific case,
3441            // we know that they will work.
3442            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3443            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3444                FileUtils.deleteContents(cacheBaseDir);
3445                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3446            }
3447        }
3448
3449        return cacheDir;
3450    }
3451
3452    @Override
3453    public boolean isFirstBoot() {
3454        // allow instant applications
3455        return mFirstBoot;
3456    }
3457
3458    @Override
3459    public boolean isOnlyCoreApps() {
3460        // allow instant applications
3461        return mOnlyCore;
3462    }
3463
3464    @Override
3465    public boolean isUpgrade() {
3466        // allow instant applications
3467        // The system property allows testing ota flow when upgraded to the same image.
3468        return mIsUpgrade || SystemProperties.getBoolean(
3469                "persist.pm.mock-upgrade", false /* default */);
3470    }
3471
3472    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3473        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3474
3475        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3476                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3477                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3478        if (matches.size() == 1) {
3479            return matches.get(0).getComponentInfo().packageName;
3480        } else if (matches.size() == 0) {
3481            Log.e(TAG, "There should probably be a verifier, but, none were found");
3482            return null;
3483        }
3484        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3485    }
3486
3487    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3488        synchronized (mPackages) {
3489            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3490            if (libraryEntry == null) {
3491                throw new IllegalStateException("Missing required shared library:" + name);
3492            }
3493            return libraryEntry.apk;
3494        }
3495    }
3496
3497    private @NonNull String getRequiredInstallerLPr() {
3498        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3499        intent.addCategory(Intent.CATEGORY_DEFAULT);
3500        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3501
3502        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3503                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3504                UserHandle.USER_SYSTEM);
3505        if (matches.size() == 1) {
3506            ResolveInfo resolveInfo = matches.get(0);
3507            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3508                throw new RuntimeException("The installer must be a privileged app");
3509            }
3510            return matches.get(0).getComponentInfo().packageName;
3511        } else {
3512            throw new RuntimeException("There must be exactly one installer; found " + matches);
3513        }
3514    }
3515
3516    private @NonNull String getRequiredUninstallerLPr() {
3517        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3518        intent.addCategory(Intent.CATEGORY_DEFAULT);
3519        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3520
3521        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3522                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3523                UserHandle.USER_SYSTEM);
3524        if (resolveInfo == null ||
3525                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3526            throw new RuntimeException("There must be exactly one uninstaller; found "
3527                    + resolveInfo);
3528        }
3529        return resolveInfo.getComponentInfo().packageName;
3530    }
3531
3532    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3533        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3534
3535        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3536                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3537                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3538        ResolveInfo best = null;
3539        final int N = matches.size();
3540        for (int i = 0; i < N; i++) {
3541            final ResolveInfo cur = matches.get(i);
3542            final String packageName = cur.getComponentInfo().packageName;
3543            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3544                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3545                continue;
3546            }
3547
3548            if (best == null || cur.priority > best.priority) {
3549                best = cur;
3550            }
3551        }
3552
3553        if (best != null) {
3554            return best.getComponentInfo().getComponentName();
3555        }
3556        Slog.w(TAG, "Intent filter verifier not found");
3557        return null;
3558    }
3559
3560    @Override
3561    public @Nullable ComponentName getInstantAppResolverComponent() {
3562        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3563            return null;
3564        }
3565        synchronized (mPackages) {
3566            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3567            if (instantAppResolver == null) {
3568                return null;
3569            }
3570            return instantAppResolver.first;
3571        }
3572    }
3573
3574    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3575        final String[] packageArray =
3576                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3577        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3578            if (DEBUG_INSTANT) {
3579                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3580            }
3581            return null;
3582        }
3583
3584        final int callingUid = Binder.getCallingUid();
3585        final int resolveFlags =
3586                MATCH_DIRECT_BOOT_AWARE
3587                | MATCH_DIRECT_BOOT_UNAWARE
3588                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3589        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3590        final Intent resolverIntent = new Intent(actionName);
3591        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3592                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3593        final int N = resolvers.size();
3594        if (N == 0) {
3595            if (DEBUG_INSTANT) {
3596                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3597            }
3598            return null;
3599        }
3600
3601        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3602        for (int i = 0; i < N; i++) {
3603            final ResolveInfo info = resolvers.get(i);
3604
3605            if (info.serviceInfo == null) {
3606                continue;
3607            }
3608
3609            final String packageName = info.serviceInfo.packageName;
3610            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3611                if (DEBUG_INSTANT) {
3612                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3613                            + " pkg: " + packageName + ", info:" + info);
3614                }
3615                continue;
3616            }
3617
3618            if (DEBUG_INSTANT) {
3619                Slog.v(TAG, "Ephemeral resolver found;"
3620                        + " pkg: " + packageName + ", info:" + info);
3621            }
3622            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3623        }
3624        if (DEBUG_INSTANT) {
3625            Slog.v(TAG, "Ephemeral resolver NOT found");
3626        }
3627        return null;
3628    }
3629
3630    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3631        String[] orderedActions = Build.IS_ENG
3632                ? new String[]{
3633                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3634                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3635                : new String[]{
3636                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3637
3638        final int resolveFlags =
3639                MATCH_DIRECT_BOOT_AWARE
3640                        | MATCH_DIRECT_BOOT_UNAWARE
3641                        | Intent.FLAG_IGNORE_EPHEMERAL
3642                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3643        final Intent intent = new Intent();
3644        intent.addCategory(Intent.CATEGORY_DEFAULT);
3645        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3646        List<ResolveInfo> matches = null;
3647        for (String action : orderedActions) {
3648            intent.setAction(action);
3649            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3650                    resolveFlags, UserHandle.USER_SYSTEM);
3651            if (matches.isEmpty()) {
3652                if (DEBUG_INSTANT) {
3653                    Slog.d(TAG, "Instant App installer not found with " + action);
3654                }
3655            } else {
3656                break;
3657            }
3658        }
3659        Iterator<ResolveInfo> iter = matches.iterator();
3660        while (iter.hasNext()) {
3661            final ResolveInfo rInfo = iter.next();
3662            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3663            if (ps != null) {
3664                final PermissionsState permissionsState = ps.getPermissionsState();
3665                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3666                        || Build.IS_ENG) {
3667                    continue;
3668                }
3669            }
3670            iter.remove();
3671        }
3672        if (matches.size() == 0) {
3673            return null;
3674        } else if (matches.size() == 1) {
3675            return (ActivityInfo) matches.get(0).getComponentInfo();
3676        } else {
3677            throw new RuntimeException(
3678                    "There must be at most one ephemeral installer; found " + matches);
3679        }
3680    }
3681
3682    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3683            @NonNull ComponentName resolver) {
3684        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3685                .addCategory(Intent.CATEGORY_DEFAULT)
3686                .setPackage(resolver.getPackageName());
3687        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3688        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3689                UserHandle.USER_SYSTEM);
3690        if (matches.isEmpty()) {
3691            return null;
3692        }
3693        return matches.get(0).getComponentInfo().getComponentName();
3694    }
3695
3696    private void primeDomainVerificationsLPw(int userId) {
3697        if (DEBUG_DOMAIN_VERIFICATION) {
3698            Slog.d(TAG, "Priming domain verifications in user " + userId);
3699        }
3700
3701        SystemConfig systemConfig = SystemConfig.getInstance();
3702        ArraySet<String> packages = systemConfig.getLinkedApps();
3703
3704        for (String packageName : packages) {
3705            PackageParser.Package pkg = mPackages.get(packageName);
3706            if (pkg != null) {
3707                if (!pkg.isSystem()) {
3708                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3709                    continue;
3710                }
3711
3712                ArraySet<String> domains = null;
3713                for (PackageParser.Activity a : pkg.activities) {
3714                    for (ActivityIntentInfo filter : a.intents) {
3715                        if (hasValidDomains(filter)) {
3716                            if (domains == null) {
3717                                domains = new ArraySet<String>();
3718                            }
3719                            domains.addAll(filter.getHostsList());
3720                        }
3721                    }
3722                }
3723
3724                if (domains != null && domains.size() > 0) {
3725                    if (DEBUG_DOMAIN_VERIFICATION) {
3726                        Slog.v(TAG, "      + " + packageName);
3727                    }
3728                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3729                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3730                    // and then 'always' in the per-user state actually used for intent resolution.
3731                    final IntentFilterVerificationInfo ivi;
3732                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3733                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3734                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3735                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3736                } else {
3737                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3738                            + "' does not handle web links");
3739                }
3740            } else {
3741                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3742            }
3743        }
3744
3745        scheduleWritePackageRestrictionsLocked(userId);
3746        scheduleWriteSettingsLocked();
3747    }
3748
3749    private void applyFactoryDefaultBrowserLPw(int userId) {
3750        // The default browser app's package name is stored in a string resource,
3751        // with a product-specific overlay used for vendor customization.
3752        String browserPkg = mContext.getResources().getString(
3753                com.android.internal.R.string.default_browser);
3754        if (!TextUtils.isEmpty(browserPkg)) {
3755            // non-empty string => required to be a known package
3756            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3757            if (ps == null) {
3758                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3759                browserPkg = null;
3760            } else {
3761                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3762            }
3763        }
3764
3765        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3766        // default.  If there's more than one, just leave everything alone.
3767        if (browserPkg == null) {
3768            calculateDefaultBrowserLPw(userId);
3769        }
3770    }
3771
3772    private void calculateDefaultBrowserLPw(int userId) {
3773        List<String> allBrowsers = resolveAllBrowserApps(userId);
3774        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3775        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3776    }
3777
3778    private List<String> resolveAllBrowserApps(int userId) {
3779        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3780        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3781                PackageManager.MATCH_ALL, userId);
3782
3783        final int count = list.size();
3784        List<String> result = new ArrayList<String>(count);
3785        for (int i=0; i<count; i++) {
3786            ResolveInfo info = list.get(i);
3787            if (info.activityInfo == null
3788                    || !info.handleAllWebDataURI
3789                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3790                    || result.contains(info.activityInfo.packageName)) {
3791                continue;
3792            }
3793            result.add(info.activityInfo.packageName);
3794        }
3795
3796        return result;
3797    }
3798
3799    private boolean packageIsBrowser(String packageName, int userId) {
3800        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3801                PackageManager.MATCH_ALL, userId);
3802        final int N = list.size();
3803        for (int i = 0; i < N; i++) {
3804            ResolveInfo info = list.get(i);
3805            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3806                return true;
3807            }
3808        }
3809        return false;
3810    }
3811
3812    private void checkDefaultBrowser() {
3813        final int myUserId = UserHandle.myUserId();
3814        final String packageName = getDefaultBrowserPackageName(myUserId);
3815        if (packageName != null) {
3816            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3817            if (info == null) {
3818                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3819                synchronized (mPackages) {
3820                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3821                }
3822            }
3823        }
3824    }
3825
3826    @Override
3827    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3828            throws RemoteException {
3829        try {
3830            return super.onTransact(code, data, reply, flags);
3831        } catch (RuntimeException e) {
3832            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3833                Slog.wtf(TAG, "Package Manager Crash", e);
3834            }
3835            throw e;
3836        }
3837    }
3838
3839    static int[] appendInts(int[] cur, int[] add) {
3840        if (add == null) return cur;
3841        if (cur == null) return add;
3842        final int N = add.length;
3843        for (int i=0; i<N; i++) {
3844            cur = appendInt(cur, add[i]);
3845        }
3846        return cur;
3847    }
3848
3849    /**
3850     * Returns whether or not a full application can see an instant application.
3851     * <p>
3852     * Currently, there are three cases in which this can occur:
3853     * <ol>
3854     * <li>The calling application is a "special" process. Special processes
3855     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3856     * <li>The calling application has the permission
3857     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3858     * <li>The calling application is the default launcher on the
3859     *     system partition.</li>
3860     * </ol>
3861     */
3862    private boolean canViewInstantApps(int callingUid, int userId) {
3863        if (callingUid < Process.FIRST_APPLICATION_UID) {
3864            return true;
3865        }
3866        if (mContext.checkCallingOrSelfPermission(
3867                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3868            return true;
3869        }
3870        if (mContext.checkCallingOrSelfPermission(
3871                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3872            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3873            if (homeComponent != null
3874                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3875                return true;
3876            }
3877        }
3878        return false;
3879    }
3880
3881    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3882        if (!sUserManager.exists(userId)) return null;
3883        if (ps == null) {
3884            return null;
3885        }
3886        final int callingUid = Binder.getCallingUid();
3887        // Filter out ephemeral app metadata:
3888        //   * The system/shell/root can see metadata for any app
3889        //   * An installed app can see metadata for 1) other installed apps
3890        //     and 2) ephemeral apps that have explicitly interacted with it
3891        //   * Ephemeral apps can only see their own data and exposed installed apps
3892        //   * Holding a signature permission allows seeing instant apps
3893        if (filterAppAccessLPr(ps, callingUid, userId)) {
3894            return null;
3895        }
3896
3897        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3898                && ps.isSystem()) {
3899            flags |= MATCH_ANY_USER;
3900        }
3901
3902        final PackageUserState state = ps.readUserState(userId);
3903        PackageParser.Package p = ps.pkg;
3904        if (p != null) {
3905            final PermissionsState permissionsState = ps.getPermissionsState();
3906
3907            // Compute GIDs only if requested
3908            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3909                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3910            // Compute granted permissions only if package has requested permissions
3911            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3912                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3913
3914            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3915                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3916
3917            if (packageInfo == null) {
3918                return null;
3919            }
3920
3921            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3922                    resolveExternalPackageNameLPr(p);
3923
3924            return packageInfo;
3925        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3926            PackageInfo pi = new PackageInfo();
3927            pi.packageName = ps.name;
3928            pi.setLongVersionCode(ps.versionCode);
3929            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3930            pi.firstInstallTime = ps.firstInstallTime;
3931            pi.lastUpdateTime = ps.lastUpdateTime;
3932
3933            ApplicationInfo ai = new ApplicationInfo();
3934            ai.packageName = ps.name;
3935            ai.uid = UserHandle.getUid(userId, ps.appId);
3936            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3937            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3938            ai.versionCode = ps.versionCode;
3939            ai.flags = ps.pkgFlags;
3940            ai.privateFlags = ps.pkgPrivateFlags;
3941            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3942
3943            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3944                    + ps.name + "]. Provides a minimum info.");
3945            return pi;
3946        } else {
3947            return null;
3948        }
3949    }
3950
3951    @Override
3952    public void checkPackageStartable(String packageName, int userId) {
3953        final int callingUid = Binder.getCallingUid();
3954        if (getInstantAppPackageName(callingUid) != null) {
3955            throw new SecurityException("Instant applications don't have access to this method");
3956        }
3957        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3958        synchronized (mPackages) {
3959            final PackageSetting ps = mSettings.mPackages.get(packageName);
3960            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3961                throw new SecurityException("Package " + packageName + " was not found!");
3962            }
3963
3964            if (!ps.getInstalled(userId)) {
3965                throw new SecurityException(
3966                        "Package " + packageName + " was not installed for user " + userId + "!");
3967            }
3968
3969            if (mSafeMode && !ps.isSystem()) {
3970                throw new SecurityException("Package " + packageName + " not a system app!");
3971            }
3972
3973            if (mFrozenPackages.contains(packageName)) {
3974                throw new SecurityException("Package " + packageName + " is currently frozen!");
3975            }
3976
3977            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3978                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3979            }
3980        }
3981    }
3982
3983    @Override
3984    public boolean isPackageAvailable(String packageName, int userId) {
3985        if (!sUserManager.exists(userId)) return false;
3986        final int callingUid = Binder.getCallingUid();
3987        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3988                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3989        synchronized (mPackages) {
3990            PackageParser.Package p = mPackages.get(packageName);
3991            if (p != null) {
3992                final PackageSetting ps = (PackageSetting) p.mExtras;
3993                if (filterAppAccessLPr(ps, callingUid, userId)) {
3994                    return false;
3995                }
3996                if (ps != null) {
3997                    final PackageUserState state = ps.readUserState(userId);
3998                    if (state != null) {
3999                        return PackageParser.isAvailable(state);
4000                    }
4001                }
4002            }
4003        }
4004        return false;
4005    }
4006
4007    @Override
4008    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4009        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4010                flags, Binder.getCallingUid(), userId);
4011    }
4012
4013    @Override
4014    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4015            int flags, int userId) {
4016        return getPackageInfoInternal(versionedPackage.getPackageName(),
4017                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4018    }
4019
4020    /**
4021     * Important: The provided filterCallingUid is used exclusively to filter out packages
4022     * that can be seen based on user state. It's typically the original caller uid prior
4023     * to clearing. Because it can only be provided by trusted code, it's value can be
4024     * trusted and will be used as-is; unlike userId which will be validated by this method.
4025     */
4026    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4027            int flags, int filterCallingUid, int userId) {
4028        if (!sUserManager.exists(userId)) return null;
4029        flags = updateFlagsForPackage(flags, userId, packageName);
4030        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4031                false /* requireFullPermission */, false /* checkShell */, "get package info");
4032
4033        // reader
4034        synchronized (mPackages) {
4035            // Normalize package name to handle renamed packages and static libs
4036            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4037
4038            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4039            if (matchFactoryOnly) {
4040                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4041                if (ps != null) {
4042                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4043                        return null;
4044                    }
4045                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4046                        return null;
4047                    }
4048                    return generatePackageInfo(ps, flags, userId);
4049                }
4050            }
4051
4052            PackageParser.Package p = mPackages.get(packageName);
4053            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4054                return null;
4055            }
4056            if (DEBUG_PACKAGE_INFO)
4057                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4058            if (p != null) {
4059                final PackageSetting ps = (PackageSetting) p.mExtras;
4060                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4061                    return null;
4062                }
4063                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4064                    return null;
4065                }
4066                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4067            }
4068            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4069                final PackageSetting ps = mSettings.mPackages.get(packageName);
4070                if (ps == null) return null;
4071                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4072                    return null;
4073                }
4074                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4075                    return null;
4076                }
4077                return generatePackageInfo(ps, flags, userId);
4078            }
4079        }
4080        return null;
4081    }
4082
4083    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4084        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4085            return true;
4086        }
4087        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4088            return true;
4089        }
4090        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4091            return true;
4092        }
4093        return false;
4094    }
4095
4096    private boolean isComponentVisibleToInstantApp(
4097            @Nullable ComponentName component, @ComponentType int type) {
4098        if (type == TYPE_ACTIVITY) {
4099            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4100            if (activity == null) {
4101                return false;
4102            }
4103            final boolean visibleToInstantApp =
4104                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4105            final boolean explicitlyVisibleToInstantApp =
4106                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4107            return visibleToInstantApp && explicitlyVisibleToInstantApp;
4108        } else if (type == TYPE_RECEIVER) {
4109            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4110            if (activity == null) {
4111                return false;
4112            }
4113            final boolean visibleToInstantApp =
4114                    (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4115            final boolean explicitlyVisibleToInstantApp =
4116                    (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4117            return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4118        } else if (type == TYPE_SERVICE) {
4119            final PackageParser.Service service = mServices.mServices.get(component);
4120            return service != null
4121                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4122                    : false;
4123        } else if (type == TYPE_PROVIDER) {
4124            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4125            return provider != null
4126                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4127                    : false;
4128        } else if (type == TYPE_UNKNOWN) {
4129            return isComponentVisibleToInstantApp(component);
4130        }
4131        return false;
4132    }
4133
4134    /**
4135     * Returns whether or not access to the application should be filtered.
4136     * <p>
4137     * Access may be limited based upon whether the calling or target applications
4138     * are instant applications.
4139     *
4140     * @see #canAccessInstantApps(int)
4141     */
4142    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4143            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4144        // if we're in an isolated process, get the real calling UID
4145        if (Process.isIsolated(callingUid)) {
4146            callingUid = mIsolatedOwners.get(callingUid);
4147        }
4148        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4149        final boolean callerIsInstantApp = instantAppPkgName != null;
4150        if (ps == null) {
4151            if (callerIsInstantApp) {
4152                // pretend the application exists, but, needs to be filtered
4153                return true;
4154            }
4155            return false;
4156        }
4157        // if the target and caller are the same application, don't filter
4158        if (isCallerSameApp(ps.name, callingUid)) {
4159            return false;
4160        }
4161        if (callerIsInstantApp) {
4162            // both caller and target are both instant, but, different applications, filter
4163            if (ps.getInstantApp(userId)) {
4164                return true;
4165            }
4166            // request for a specific component; if it hasn't been explicitly exposed through
4167            // property or instrumentation target, filter
4168            if (component != null) {
4169                final PackageParser.Instrumentation instrumentation =
4170                        mInstrumentation.get(component);
4171                if (instrumentation != null
4172                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4173                    return false;
4174                }
4175                return !isComponentVisibleToInstantApp(component, componentType);
4176            }
4177            // request for application; if no components have been explicitly exposed, filter
4178            return !ps.pkg.visibleToInstantApps;
4179        }
4180        if (ps.getInstantApp(userId)) {
4181            // caller can see all components of all instant applications, don't filter
4182            if (canViewInstantApps(callingUid, userId)) {
4183                return false;
4184            }
4185            // request for a specific instant application component, filter
4186            if (component != null) {
4187                return true;
4188            }
4189            // request for an instant application; if the caller hasn't been granted access, filter
4190            return !mInstantAppRegistry.isInstantAccessGranted(
4191                    userId, UserHandle.getAppId(callingUid), ps.appId);
4192        }
4193        return false;
4194    }
4195
4196    /**
4197     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4198     */
4199    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4200        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4201    }
4202
4203    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4204            int flags) {
4205        // Callers can access only the libs they depend on, otherwise they need to explicitly
4206        // ask for the shared libraries given the caller is allowed to access all static libs.
4207        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4208            // System/shell/root get to see all static libs
4209            final int appId = UserHandle.getAppId(uid);
4210            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4211                    || appId == Process.ROOT_UID) {
4212                return false;
4213            }
4214        }
4215
4216        // No package means no static lib as it is always on internal storage
4217        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4218            return false;
4219        }
4220
4221        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4222                ps.pkg.staticSharedLibVersion);
4223        if (libEntry == null) {
4224            return false;
4225        }
4226
4227        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4228        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4229        if (uidPackageNames == null) {
4230            return true;
4231        }
4232
4233        for (String uidPackageName : uidPackageNames) {
4234            if (ps.name.equals(uidPackageName)) {
4235                return false;
4236            }
4237            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4238            if (uidPs != null) {
4239                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4240                        libEntry.info.getName());
4241                if (index < 0) {
4242                    continue;
4243                }
4244                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4245                    return false;
4246                }
4247            }
4248        }
4249        return true;
4250    }
4251
4252    @Override
4253    public String[] currentToCanonicalPackageNames(String[] names) {
4254        final int callingUid = Binder.getCallingUid();
4255        if (getInstantAppPackageName(callingUid) != null) {
4256            return names;
4257        }
4258        final String[] out = new String[names.length];
4259        // reader
4260        synchronized (mPackages) {
4261            final int callingUserId = UserHandle.getUserId(callingUid);
4262            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4263            for (int i=names.length-1; i>=0; i--) {
4264                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4265                boolean translateName = false;
4266                if (ps != null && ps.realName != null) {
4267                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4268                    translateName = !targetIsInstantApp
4269                            || canViewInstantApps
4270                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4271                                    UserHandle.getAppId(callingUid), ps.appId);
4272                }
4273                out[i] = translateName ? ps.realName : names[i];
4274            }
4275        }
4276        return out;
4277    }
4278
4279    @Override
4280    public String[] canonicalToCurrentPackageNames(String[] names) {
4281        final int callingUid = Binder.getCallingUid();
4282        if (getInstantAppPackageName(callingUid) != null) {
4283            return names;
4284        }
4285        final String[] out = new String[names.length];
4286        // reader
4287        synchronized (mPackages) {
4288            final int callingUserId = UserHandle.getUserId(callingUid);
4289            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4290            for (int i=names.length-1; i>=0; i--) {
4291                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4292                boolean translateName = false;
4293                if (cur != null) {
4294                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4295                    final boolean targetIsInstantApp =
4296                            ps != null && ps.getInstantApp(callingUserId);
4297                    translateName = !targetIsInstantApp
4298                            || canViewInstantApps
4299                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4300                                    UserHandle.getAppId(callingUid), ps.appId);
4301                }
4302                out[i] = translateName ? cur : names[i];
4303            }
4304        }
4305        return out;
4306    }
4307
4308    @Override
4309    public int getPackageUid(String packageName, int flags, int userId) {
4310        if (!sUserManager.exists(userId)) return -1;
4311        final int callingUid = Binder.getCallingUid();
4312        flags = updateFlagsForPackage(flags, userId, packageName);
4313        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4314                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4315
4316        // reader
4317        synchronized (mPackages) {
4318            final PackageParser.Package p = mPackages.get(packageName);
4319            if (p != null && p.isMatch(flags)) {
4320                PackageSetting ps = (PackageSetting) p.mExtras;
4321                if (filterAppAccessLPr(ps, callingUid, userId)) {
4322                    return -1;
4323                }
4324                return UserHandle.getUid(userId, p.applicationInfo.uid);
4325            }
4326            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4327                final PackageSetting ps = mSettings.mPackages.get(packageName);
4328                if (ps != null && ps.isMatch(flags)
4329                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4330                    return UserHandle.getUid(userId, ps.appId);
4331                }
4332            }
4333        }
4334
4335        return -1;
4336    }
4337
4338    @Override
4339    public int[] getPackageGids(String packageName, int flags, int userId) {
4340        if (!sUserManager.exists(userId)) return null;
4341        final int callingUid = Binder.getCallingUid();
4342        flags = updateFlagsForPackage(flags, userId, packageName);
4343        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4344                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4345
4346        // reader
4347        synchronized (mPackages) {
4348            final PackageParser.Package p = mPackages.get(packageName);
4349            if (p != null && p.isMatch(flags)) {
4350                PackageSetting ps = (PackageSetting) p.mExtras;
4351                if (filterAppAccessLPr(ps, callingUid, userId)) {
4352                    return null;
4353                }
4354                // TODO: Shouldn't this be checking for package installed state for userId and
4355                // return null?
4356                return ps.getPermissionsState().computeGids(userId);
4357            }
4358            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4359                final PackageSetting ps = mSettings.mPackages.get(packageName);
4360                if (ps != null && ps.isMatch(flags)
4361                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4362                    return ps.getPermissionsState().computeGids(userId);
4363                }
4364            }
4365        }
4366
4367        return null;
4368    }
4369
4370    @Override
4371    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4372        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4373    }
4374
4375    @Override
4376    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4377            int flags) {
4378        final List<PermissionInfo> permissionList =
4379                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4380        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4381    }
4382
4383    @Override
4384    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4385        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4386    }
4387
4388    @Override
4389    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4390        final List<PermissionGroupInfo> permissionList =
4391                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4392        return (permissionList == null)
4393                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4394    }
4395
4396    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4397            int filterCallingUid, int userId) {
4398        if (!sUserManager.exists(userId)) return null;
4399        PackageSetting ps = mSettings.mPackages.get(packageName);
4400        if (ps != null) {
4401            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4402                return null;
4403            }
4404            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4405                return null;
4406            }
4407            if (ps.pkg == null) {
4408                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4409                if (pInfo != null) {
4410                    return pInfo.applicationInfo;
4411                }
4412                return null;
4413            }
4414            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4415                    ps.readUserState(userId), userId);
4416            if (ai != null) {
4417                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4418            }
4419            return ai;
4420        }
4421        return null;
4422    }
4423
4424    @Override
4425    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4426        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4427    }
4428
4429    /**
4430     * Important: The provided filterCallingUid is used exclusively to filter out applications
4431     * that can be seen based on user state. It's typically the original caller uid prior
4432     * to clearing. Because it can only be provided by trusted code, it's value can be
4433     * trusted and will be used as-is; unlike userId which will be validated by this method.
4434     */
4435    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4436            int filterCallingUid, int userId) {
4437        if (!sUserManager.exists(userId)) return null;
4438        flags = updateFlagsForApplication(flags, userId, packageName);
4439        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4440                false /* requireFullPermission */, false /* checkShell */, "get application info");
4441
4442        // writer
4443        synchronized (mPackages) {
4444            // Normalize package name to handle renamed packages and static libs
4445            packageName = resolveInternalPackageNameLPr(packageName,
4446                    PackageManager.VERSION_CODE_HIGHEST);
4447
4448            PackageParser.Package p = mPackages.get(packageName);
4449            if (DEBUG_PACKAGE_INFO) Log.v(
4450                    TAG, "getApplicationInfo " + packageName
4451                    + ": " + p);
4452            if (p != null) {
4453                PackageSetting ps = mSettings.mPackages.get(packageName);
4454                if (ps == null) return null;
4455                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4456                    return null;
4457                }
4458                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4459                    return null;
4460                }
4461                // Note: isEnabledLP() does not apply here - always return info
4462                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4463                        p, flags, ps.readUserState(userId), userId);
4464                if (ai != null) {
4465                    ai.packageName = resolveExternalPackageNameLPr(p);
4466                }
4467                return ai;
4468            }
4469            if ("android".equals(packageName)||"system".equals(packageName)) {
4470                return mAndroidApplication;
4471            }
4472            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4473                // Already generates the external package name
4474                return generateApplicationInfoFromSettingsLPw(packageName,
4475                        flags, filterCallingUid, userId);
4476            }
4477        }
4478        return null;
4479    }
4480
4481    private String normalizePackageNameLPr(String packageName) {
4482        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4483        return normalizedPackageName != null ? normalizedPackageName : packageName;
4484    }
4485
4486    @Override
4487    public void deletePreloadsFileCache() {
4488        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4489            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4490        }
4491        File dir = Environment.getDataPreloadsFileCacheDirectory();
4492        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4493        FileUtils.deleteContents(dir);
4494    }
4495
4496    @Override
4497    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4498            final int storageFlags, final IPackageDataObserver observer) {
4499        mContext.enforceCallingOrSelfPermission(
4500                android.Manifest.permission.CLEAR_APP_CACHE, null);
4501        mHandler.post(() -> {
4502            boolean success = false;
4503            try {
4504                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4505                success = true;
4506            } catch (IOException e) {
4507                Slog.w(TAG, e);
4508            }
4509            if (observer != null) {
4510                try {
4511                    observer.onRemoveCompleted(null, success);
4512                } catch (RemoteException e) {
4513                    Slog.w(TAG, e);
4514                }
4515            }
4516        });
4517    }
4518
4519    @Override
4520    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4521            final int storageFlags, final IntentSender pi) {
4522        mContext.enforceCallingOrSelfPermission(
4523                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4524        mHandler.post(() -> {
4525            boolean success = false;
4526            try {
4527                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4528                success = true;
4529            } catch (IOException e) {
4530                Slog.w(TAG, e);
4531            }
4532            if (pi != null) {
4533                try {
4534                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4535                } catch (SendIntentException e) {
4536                    Slog.w(TAG, e);
4537                }
4538            }
4539        });
4540    }
4541
4542    /**
4543     * Blocking call to clear various types of cached data across the system
4544     * until the requested bytes are available.
4545     */
4546    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4547        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4548        final File file = storage.findPathForUuid(volumeUuid);
4549        if (file.getUsableSpace() >= bytes) return;
4550
4551        if (ENABLE_FREE_CACHE_V2) {
4552            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4553                    volumeUuid);
4554            final boolean aggressive = (storageFlags
4555                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4556            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4557
4558            // 1. Pre-flight to determine if we have any chance to succeed
4559            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4560            if (internalVolume && (aggressive || SystemProperties
4561                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4562                deletePreloadsFileCache();
4563                if (file.getUsableSpace() >= bytes) return;
4564            }
4565
4566            // 3. Consider parsed APK data (aggressive only)
4567            if (internalVolume && aggressive) {
4568                FileUtils.deleteContents(mCacheDir);
4569                if (file.getUsableSpace() >= bytes) return;
4570            }
4571
4572            // 4. Consider cached app data (above quotas)
4573            try {
4574                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4575                        Installer.FLAG_FREE_CACHE_V2);
4576            } catch (InstallerException ignored) {
4577            }
4578            if (file.getUsableSpace() >= bytes) return;
4579
4580            // 5. Consider shared libraries with refcount=0 and age>min cache period
4581            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4582                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4583                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4584                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4585                return;
4586            }
4587
4588            // 6. Consider dexopt output (aggressive only)
4589            // TODO: Implement
4590
4591            // 7. Consider installed instant apps unused longer than min cache period
4592            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4593                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4594                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4595                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4596                return;
4597            }
4598
4599            // 8. Consider cached app data (below quotas)
4600            try {
4601                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4602                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4603            } catch (InstallerException ignored) {
4604            }
4605            if (file.getUsableSpace() >= bytes) return;
4606
4607            // 9. Consider DropBox entries
4608            // TODO: Implement
4609
4610            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4611            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4612                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4613                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4614                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4615                return;
4616            }
4617        } else {
4618            try {
4619                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4620            } catch (InstallerException ignored) {
4621            }
4622            if (file.getUsableSpace() >= bytes) return;
4623        }
4624
4625        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4626    }
4627
4628    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4629            throws IOException {
4630        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4631        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4632
4633        List<VersionedPackage> packagesToDelete = null;
4634        final long now = System.currentTimeMillis();
4635
4636        synchronized (mPackages) {
4637            final int[] allUsers = sUserManager.getUserIds();
4638            final int libCount = mSharedLibraries.size();
4639            for (int i = 0; i < libCount; i++) {
4640                final LongSparseArray<SharedLibraryEntry> versionedLib
4641                        = mSharedLibraries.valueAt(i);
4642                if (versionedLib == null) {
4643                    continue;
4644                }
4645                final int versionCount = versionedLib.size();
4646                for (int j = 0; j < versionCount; j++) {
4647                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4648                    // Skip packages that are not static shared libs.
4649                    if (!libInfo.isStatic()) {
4650                        break;
4651                    }
4652                    // Important: We skip static shared libs used for some user since
4653                    // in such a case we need to keep the APK on the device. The check for
4654                    // a lib being used for any user is performed by the uninstall call.
4655                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4656                    // Resolve the package name - we use synthetic package names internally
4657                    final String internalPackageName = resolveInternalPackageNameLPr(
4658                            declaringPackage.getPackageName(),
4659                            declaringPackage.getLongVersionCode());
4660                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4661                    // Skip unused static shared libs cached less than the min period
4662                    // to prevent pruning a lib needed by a subsequently installed package.
4663                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4664                        continue;
4665                    }
4666                    if (packagesToDelete == null) {
4667                        packagesToDelete = new ArrayList<>();
4668                    }
4669                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4670                            declaringPackage.getLongVersionCode()));
4671                }
4672            }
4673        }
4674
4675        if (packagesToDelete != null) {
4676            final int packageCount = packagesToDelete.size();
4677            for (int i = 0; i < packageCount; i++) {
4678                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4679                // Delete the package synchronously (will fail of the lib used for any user).
4680                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4681                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4682                                == PackageManager.DELETE_SUCCEEDED) {
4683                    if (volume.getUsableSpace() >= neededSpace) {
4684                        return true;
4685                    }
4686                }
4687            }
4688        }
4689
4690        return false;
4691    }
4692
4693    /**
4694     * Update given flags based on encryption status of current user.
4695     */
4696    private int updateFlags(int flags, int userId) {
4697        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4698                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4699            // Caller expressed an explicit opinion about what encryption
4700            // aware/unaware components they want to see, so fall through and
4701            // give them what they want
4702        } else {
4703            // Caller expressed no opinion, so match based on user state
4704            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4705                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4706            } else {
4707                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4708            }
4709        }
4710        return flags;
4711    }
4712
4713    private UserManagerInternal getUserManagerInternal() {
4714        if (mUserManagerInternal == null) {
4715            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4716        }
4717        return mUserManagerInternal;
4718    }
4719
4720    private ActivityManagerInternal getActivityManagerInternal() {
4721        if (mActivityManagerInternal == null) {
4722            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4723        }
4724        return mActivityManagerInternal;
4725    }
4726
4727
4728    private DeviceIdleController.LocalService getDeviceIdleController() {
4729        if (mDeviceIdleController == null) {
4730            mDeviceIdleController =
4731                    LocalServices.getService(DeviceIdleController.LocalService.class);
4732        }
4733        return mDeviceIdleController;
4734    }
4735
4736    /**
4737     * Update given flags when being used to request {@link PackageInfo}.
4738     */
4739    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4740        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4741        boolean triaged = true;
4742        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4743                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4744            // Caller is asking for component details, so they'd better be
4745            // asking for specific encryption matching behavior, or be triaged
4746            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4747                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4748                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4749                triaged = false;
4750            }
4751        }
4752        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4753                | PackageManager.MATCH_SYSTEM_ONLY
4754                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4755            triaged = false;
4756        }
4757        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4758            mPermissionManager.enforceCrossUserPermission(
4759                    Binder.getCallingUid(), userId, false, false,
4760                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4761                    + Debug.getCallers(5));
4762        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4763                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4764            // If the caller wants all packages and has a restricted profile associated with it,
4765            // then match all users. This is to make sure that launchers that need to access work
4766            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4767            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4768            flags |= PackageManager.MATCH_ANY_USER;
4769        }
4770        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4771            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4772                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4773        }
4774        return updateFlags(flags, userId);
4775    }
4776
4777    /**
4778     * Update given flags when being used to request {@link ApplicationInfo}.
4779     */
4780    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4781        return updateFlagsForPackage(flags, userId, cookie);
4782    }
4783
4784    /**
4785     * Update given flags when being used to request {@link ComponentInfo}.
4786     */
4787    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4788        if (cookie instanceof Intent) {
4789            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4790                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4791            }
4792        }
4793
4794        boolean triaged = true;
4795        // Caller is asking for component details, so they'd better be
4796        // asking for specific encryption matching behavior, or be triaged
4797        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4798                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4799                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4800            triaged = false;
4801        }
4802        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4803            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4804                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4805        }
4806
4807        return updateFlags(flags, userId);
4808    }
4809
4810    /**
4811     * Update given intent when being used to request {@link ResolveInfo}.
4812     */
4813    private Intent updateIntentForResolve(Intent intent) {
4814        if (intent.getSelector() != null) {
4815            intent = intent.getSelector();
4816        }
4817        if (DEBUG_PREFERRED) {
4818            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4819        }
4820        return intent;
4821    }
4822
4823    /**
4824     * Update given flags when being used to request {@link ResolveInfo}.
4825     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4826     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4827     * flag set. However, this flag is only honoured in three circumstances:
4828     * <ul>
4829     * <li>when called from a system process</li>
4830     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4831     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4832     * action and a {@code android.intent.category.BROWSABLE} category</li>
4833     * </ul>
4834     */
4835    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4836        return updateFlagsForResolve(flags, userId, intent, callingUid,
4837                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4838    }
4839    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4840            boolean wantInstantApps) {
4841        return updateFlagsForResolve(flags, userId, intent, callingUid,
4842                wantInstantApps, false /*onlyExposedExplicitly*/);
4843    }
4844    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4845            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4846        // Safe mode means we shouldn't match any third-party components
4847        if (mSafeMode) {
4848            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4849        }
4850        if (getInstantAppPackageName(callingUid) != null) {
4851            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4852            if (onlyExposedExplicitly) {
4853                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4854            }
4855            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4856            flags |= PackageManager.MATCH_INSTANT;
4857        } else {
4858            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4859            final boolean allowMatchInstant = wantInstantApps
4860                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4861            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4862                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4863            if (!allowMatchInstant) {
4864                flags &= ~PackageManager.MATCH_INSTANT;
4865            }
4866        }
4867        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4868    }
4869
4870    @Override
4871    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4872        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4873    }
4874
4875    /**
4876     * Important: The provided filterCallingUid is used exclusively to filter out activities
4877     * that can be seen based on user state. It's typically the original caller uid prior
4878     * to clearing. Because it can only be provided by trusted code, it's value can be
4879     * trusted and will be used as-is; unlike userId which will be validated by this method.
4880     */
4881    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4882            int filterCallingUid, int userId) {
4883        if (!sUserManager.exists(userId)) return null;
4884        flags = updateFlagsForComponent(flags, userId, component);
4885
4886        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4887            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4888                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4889        }
4890
4891        synchronized (mPackages) {
4892            PackageParser.Activity a = mActivities.mActivities.get(component);
4893
4894            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4895            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4896                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4897                if (ps == null) return null;
4898                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4899                    return null;
4900                }
4901                return PackageParser.generateActivityInfo(
4902                        a, flags, ps.readUserState(userId), userId);
4903            }
4904            if (mResolveComponentName.equals(component)) {
4905                return PackageParser.generateActivityInfo(
4906                        mResolveActivity, flags, new PackageUserState(), userId);
4907            }
4908        }
4909        return null;
4910    }
4911
4912    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4913        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4914            return false;
4915        }
4916        final long token = Binder.clearCallingIdentity();
4917        try {
4918            final int callingUserId = UserHandle.getUserId(callingUid);
4919            if (ActivityManager.getCurrentUser() != callingUserId) {
4920                return false;
4921            }
4922            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4923        } finally {
4924            Binder.restoreCallingIdentity(token);
4925        }
4926    }
4927
4928    @Override
4929    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4930            String resolvedType) {
4931        synchronized (mPackages) {
4932            if (component.equals(mResolveComponentName)) {
4933                // The resolver supports EVERYTHING!
4934                return true;
4935            }
4936            final int callingUid = Binder.getCallingUid();
4937            final int callingUserId = UserHandle.getUserId(callingUid);
4938            PackageParser.Activity a = mActivities.mActivities.get(component);
4939            if (a == null) {
4940                return false;
4941            }
4942            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4943            if (ps == null) {
4944                return false;
4945            }
4946            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4947                return false;
4948            }
4949            for (int i=0; i<a.intents.size(); i++) {
4950                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4951                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4952                    return true;
4953                }
4954            }
4955            return false;
4956        }
4957    }
4958
4959    @Override
4960    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4961        if (!sUserManager.exists(userId)) return null;
4962        final int callingUid = Binder.getCallingUid();
4963        flags = updateFlagsForComponent(flags, userId, component);
4964        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4965                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4966        synchronized (mPackages) {
4967            PackageParser.Activity a = mReceivers.mActivities.get(component);
4968            if (DEBUG_PACKAGE_INFO) Log.v(
4969                TAG, "getReceiverInfo " + component + ": " + a);
4970            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4971                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4972                if (ps == null) return null;
4973                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4974                    return null;
4975                }
4976                return PackageParser.generateActivityInfo(
4977                        a, flags, ps.readUserState(userId), userId);
4978            }
4979        }
4980        return null;
4981    }
4982
4983    @Override
4984    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4985            int flags, int userId) {
4986        if (!sUserManager.exists(userId)) return null;
4987        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4988        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4989            return null;
4990        }
4991
4992        flags = updateFlagsForPackage(flags, userId, null);
4993
4994        final boolean canSeeStaticLibraries =
4995                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4996                        == PERMISSION_GRANTED
4997                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4998                        == PERMISSION_GRANTED
4999                || canRequestPackageInstallsInternal(packageName,
5000                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5001                        false  /* throwIfPermNotDeclared*/)
5002                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5003                        == PERMISSION_GRANTED;
5004
5005        synchronized (mPackages) {
5006            List<SharedLibraryInfo> result = null;
5007
5008            final int libCount = mSharedLibraries.size();
5009            for (int i = 0; i < libCount; i++) {
5010                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5011                if (versionedLib == null) {
5012                    continue;
5013                }
5014
5015                final int versionCount = versionedLib.size();
5016                for (int j = 0; j < versionCount; j++) {
5017                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5018                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5019                        break;
5020                    }
5021                    final long identity = Binder.clearCallingIdentity();
5022                    try {
5023                        PackageInfo packageInfo = getPackageInfoVersioned(
5024                                libInfo.getDeclaringPackage(), flags
5025                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5026                        if (packageInfo == null) {
5027                            continue;
5028                        }
5029                    } finally {
5030                        Binder.restoreCallingIdentity(identity);
5031                    }
5032
5033                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5034                            libInfo.getLongVersion(), libInfo.getType(),
5035                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5036                            flags, userId));
5037
5038                    if (result == null) {
5039                        result = new ArrayList<>();
5040                    }
5041                    result.add(resLibInfo);
5042                }
5043            }
5044
5045            return result != null ? new ParceledListSlice<>(result) : null;
5046        }
5047    }
5048
5049    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5050            SharedLibraryInfo libInfo, int flags, int userId) {
5051        List<VersionedPackage> versionedPackages = null;
5052        final int packageCount = mSettings.mPackages.size();
5053        for (int i = 0; i < packageCount; i++) {
5054            PackageSetting ps = mSettings.mPackages.valueAt(i);
5055
5056            if (ps == null) {
5057                continue;
5058            }
5059
5060            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5061                continue;
5062            }
5063
5064            final String libName = libInfo.getName();
5065            if (libInfo.isStatic()) {
5066                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5067                if (libIdx < 0) {
5068                    continue;
5069                }
5070                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5071                    continue;
5072                }
5073                if (versionedPackages == null) {
5074                    versionedPackages = new ArrayList<>();
5075                }
5076                // If the dependent is a static shared lib, use the public package name
5077                String dependentPackageName = ps.name;
5078                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5079                    dependentPackageName = ps.pkg.manifestPackageName;
5080                }
5081                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5082            } else if (ps.pkg != null) {
5083                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5084                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5085                    if (versionedPackages == null) {
5086                        versionedPackages = new ArrayList<>();
5087                    }
5088                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5089                }
5090            }
5091        }
5092
5093        return versionedPackages;
5094    }
5095
5096    @Override
5097    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5098        if (!sUserManager.exists(userId)) return null;
5099        final int callingUid = Binder.getCallingUid();
5100        flags = updateFlagsForComponent(flags, userId, component);
5101        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5102                false /* requireFullPermission */, false /* checkShell */, "get service info");
5103        synchronized (mPackages) {
5104            PackageParser.Service s = mServices.mServices.get(component);
5105            if (DEBUG_PACKAGE_INFO) Log.v(
5106                TAG, "getServiceInfo " + component + ": " + s);
5107            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5108                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5109                if (ps == null) return null;
5110                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5111                    return null;
5112                }
5113                return PackageParser.generateServiceInfo(
5114                        s, flags, ps.readUserState(userId), userId);
5115            }
5116        }
5117        return null;
5118    }
5119
5120    @Override
5121    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5122        if (!sUserManager.exists(userId)) return null;
5123        final int callingUid = Binder.getCallingUid();
5124        flags = updateFlagsForComponent(flags, userId, component);
5125        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5126                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5127        synchronized (mPackages) {
5128            PackageParser.Provider p = mProviders.mProviders.get(component);
5129            if (DEBUG_PACKAGE_INFO) Log.v(
5130                TAG, "getProviderInfo " + component + ": " + p);
5131            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5132                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5133                if (ps == null) return null;
5134                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5135                    return null;
5136                }
5137                return PackageParser.generateProviderInfo(
5138                        p, flags, ps.readUserState(userId), userId);
5139            }
5140        }
5141        return null;
5142    }
5143
5144    @Override
5145    public String[] getSystemSharedLibraryNames() {
5146        // allow instant applications
5147        synchronized (mPackages) {
5148            Set<String> libs = null;
5149            final int libCount = mSharedLibraries.size();
5150            for (int i = 0; i < libCount; i++) {
5151                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5152                if (versionedLib == null) {
5153                    continue;
5154                }
5155                final int versionCount = versionedLib.size();
5156                for (int j = 0; j < versionCount; j++) {
5157                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5158                    if (!libEntry.info.isStatic()) {
5159                        if (libs == null) {
5160                            libs = new ArraySet<>();
5161                        }
5162                        libs.add(libEntry.info.getName());
5163                        break;
5164                    }
5165                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5166                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5167                            UserHandle.getUserId(Binder.getCallingUid()),
5168                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5169                        if (libs == null) {
5170                            libs = new ArraySet<>();
5171                        }
5172                        libs.add(libEntry.info.getName());
5173                        break;
5174                    }
5175                }
5176            }
5177
5178            if (libs != null) {
5179                String[] libsArray = new String[libs.size()];
5180                libs.toArray(libsArray);
5181                return libsArray;
5182            }
5183
5184            return null;
5185        }
5186    }
5187
5188    @Override
5189    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5190        // allow instant applications
5191        synchronized (mPackages) {
5192            return mServicesSystemSharedLibraryPackageName;
5193        }
5194    }
5195
5196    @Override
5197    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5198        // allow instant applications
5199        synchronized (mPackages) {
5200            return mSharedSystemSharedLibraryPackageName;
5201        }
5202    }
5203
5204    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5205        for (int i = userList.length - 1; i >= 0; --i) {
5206            final int userId = userList[i];
5207            // don't add instant app to the list of updates
5208            if (pkgSetting.getInstantApp(userId)) {
5209                continue;
5210            }
5211            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5212            if (changedPackages == null) {
5213                changedPackages = new SparseArray<>();
5214                mChangedPackages.put(userId, changedPackages);
5215            }
5216            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5217            if (sequenceNumbers == null) {
5218                sequenceNumbers = new HashMap<>();
5219                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5220            }
5221            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5222            if (sequenceNumber != null) {
5223                changedPackages.remove(sequenceNumber);
5224            }
5225            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5226            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5227        }
5228        mChangedPackagesSequenceNumber++;
5229    }
5230
5231    @Override
5232    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5233        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5234            return null;
5235        }
5236        synchronized (mPackages) {
5237            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5238                return null;
5239            }
5240            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5241            if (changedPackages == null) {
5242                return null;
5243            }
5244            final List<String> packageNames =
5245                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5246            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5247                final String packageName = changedPackages.get(i);
5248                if (packageName != null) {
5249                    packageNames.add(packageName);
5250                }
5251            }
5252            return packageNames.isEmpty()
5253                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5254        }
5255    }
5256
5257    @Override
5258    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5259        // allow instant applications
5260        ArrayList<FeatureInfo> res;
5261        synchronized (mAvailableFeatures) {
5262            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5263            res.addAll(mAvailableFeatures.values());
5264        }
5265        final FeatureInfo fi = new FeatureInfo();
5266        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5267                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5268        res.add(fi);
5269
5270        return new ParceledListSlice<>(res);
5271    }
5272
5273    @Override
5274    public boolean hasSystemFeature(String name, int version) {
5275        // allow instant applications
5276        synchronized (mAvailableFeatures) {
5277            final FeatureInfo feat = mAvailableFeatures.get(name);
5278            if (feat == null) {
5279                return false;
5280            } else {
5281                return feat.version >= version;
5282            }
5283        }
5284    }
5285
5286    @Override
5287    public int checkPermission(String permName, String pkgName, int userId) {
5288        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5289    }
5290
5291    @Override
5292    public int checkUidPermission(String permName, int uid) {
5293        synchronized (mPackages) {
5294            final String[] packageNames = getPackagesForUid(uid);
5295            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5296                    ? mPackages.get(packageNames[0])
5297                    : null;
5298            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5299        }
5300    }
5301
5302    @Override
5303    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5304        if (UserHandle.getCallingUserId() != userId) {
5305            mContext.enforceCallingPermission(
5306                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5307                    "isPermissionRevokedByPolicy for user " + userId);
5308        }
5309
5310        if (checkPermission(permission, packageName, userId)
5311                == PackageManager.PERMISSION_GRANTED) {
5312            return false;
5313        }
5314
5315        final int callingUid = Binder.getCallingUid();
5316        if (getInstantAppPackageName(callingUid) != null) {
5317            if (!isCallerSameApp(packageName, callingUid)) {
5318                return false;
5319            }
5320        } else {
5321            if (isInstantApp(packageName, userId)) {
5322                return false;
5323            }
5324        }
5325
5326        final long identity = Binder.clearCallingIdentity();
5327        try {
5328            final int flags = getPermissionFlags(permission, packageName, userId);
5329            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5330        } finally {
5331            Binder.restoreCallingIdentity(identity);
5332        }
5333    }
5334
5335    @Override
5336    public String getPermissionControllerPackageName() {
5337        synchronized (mPackages) {
5338            return mRequiredInstallerPackage;
5339        }
5340    }
5341
5342    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5343        return mPermissionManager.addDynamicPermission(
5344                info, async, getCallingUid(), new PermissionCallback() {
5345                    @Override
5346                    public void onPermissionChanged() {
5347                        if (!async) {
5348                            mSettings.writeLPr();
5349                        } else {
5350                            scheduleWriteSettingsLocked();
5351                        }
5352                    }
5353                });
5354    }
5355
5356    @Override
5357    public boolean addPermission(PermissionInfo info) {
5358        synchronized (mPackages) {
5359            return addDynamicPermission(info, false);
5360        }
5361    }
5362
5363    @Override
5364    public boolean addPermissionAsync(PermissionInfo info) {
5365        synchronized (mPackages) {
5366            return addDynamicPermission(info, true);
5367        }
5368    }
5369
5370    @Override
5371    public void removePermission(String permName) {
5372        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5373    }
5374
5375    @Override
5376    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5377        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5378                getCallingUid(), userId, mPermissionCallback);
5379    }
5380
5381    @Override
5382    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5383        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5384                getCallingUid(), userId, mPermissionCallback);
5385    }
5386
5387    @Override
5388    public void resetRuntimePermissions() {
5389        mContext.enforceCallingOrSelfPermission(
5390                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5391                "revokeRuntimePermission");
5392
5393        int callingUid = Binder.getCallingUid();
5394        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5395            mContext.enforceCallingOrSelfPermission(
5396                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5397                    "resetRuntimePermissions");
5398        }
5399
5400        synchronized (mPackages) {
5401            mPermissionManager.updateAllPermissions(
5402                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5403                    mPermissionCallback);
5404            for (int userId : UserManagerService.getInstance().getUserIds()) {
5405                final int packageCount = mPackages.size();
5406                for (int i = 0; i < packageCount; i++) {
5407                    PackageParser.Package pkg = mPackages.valueAt(i);
5408                    if (!(pkg.mExtras instanceof PackageSetting)) {
5409                        continue;
5410                    }
5411                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5412                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5413                }
5414            }
5415        }
5416    }
5417
5418    @Override
5419    public int getPermissionFlags(String permName, String packageName, int userId) {
5420        return mPermissionManager.getPermissionFlags(
5421                permName, packageName, getCallingUid(), userId);
5422    }
5423
5424    @Override
5425    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5426            int flagValues, int userId) {
5427        mPermissionManager.updatePermissionFlags(
5428                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5429                mPermissionCallback);
5430    }
5431
5432    /**
5433     * Update the permission flags for all packages and runtime permissions of a user in order
5434     * to allow device or profile owner to remove POLICY_FIXED.
5435     */
5436    @Override
5437    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5438        synchronized (mPackages) {
5439            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5440                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5441                    mPermissionCallback);
5442            if (changed) {
5443                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5444            }
5445        }
5446    }
5447
5448    @Override
5449    public boolean shouldShowRequestPermissionRationale(String permissionName,
5450            String packageName, int userId) {
5451        if (UserHandle.getCallingUserId() != userId) {
5452            mContext.enforceCallingPermission(
5453                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5454                    "canShowRequestPermissionRationale for user " + userId);
5455        }
5456
5457        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5458        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5459            return false;
5460        }
5461
5462        if (checkPermission(permissionName, packageName, userId)
5463                == PackageManager.PERMISSION_GRANTED) {
5464            return false;
5465        }
5466
5467        final int flags;
5468
5469        final long identity = Binder.clearCallingIdentity();
5470        try {
5471            flags = getPermissionFlags(permissionName,
5472                    packageName, userId);
5473        } finally {
5474            Binder.restoreCallingIdentity(identity);
5475        }
5476
5477        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5478                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5479                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5480
5481        if ((flags & fixedFlags) != 0) {
5482            return false;
5483        }
5484
5485        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5486    }
5487
5488    @Override
5489    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5490        mContext.enforceCallingOrSelfPermission(
5491                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5492                "addOnPermissionsChangeListener");
5493
5494        synchronized (mPackages) {
5495            mOnPermissionChangeListeners.addListenerLocked(listener);
5496        }
5497    }
5498
5499    @Override
5500    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5501        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5502            throw new SecurityException("Instant applications don't have access to this method");
5503        }
5504        synchronized (mPackages) {
5505            mOnPermissionChangeListeners.removeListenerLocked(listener);
5506        }
5507    }
5508
5509    @Override
5510    public boolean isProtectedBroadcast(String actionName) {
5511        // allow instant applications
5512        synchronized (mProtectedBroadcasts) {
5513            if (mProtectedBroadcasts.contains(actionName)) {
5514                return true;
5515            } else if (actionName != null) {
5516                // TODO: remove these terrible hacks
5517                if (actionName.startsWith("android.net.netmon.lingerExpired")
5518                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5519                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5520                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5521                    return true;
5522                }
5523            }
5524        }
5525        return false;
5526    }
5527
5528    @Override
5529    public int checkSignatures(String pkg1, String pkg2) {
5530        synchronized (mPackages) {
5531            final PackageParser.Package p1 = mPackages.get(pkg1);
5532            final PackageParser.Package p2 = mPackages.get(pkg2);
5533            if (p1 == null || p1.mExtras == null
5534                    || p2 == null || p2.mExtras == null) {
5535                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5536            }
5537            final int callingUid = Binder.getCallingUid();
5538            final int callingUserId = UserHandle.getUserId(callingUid);
5539            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5540            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5541            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5542                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5543                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5544            }
5545            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5546        }
5547    }
5548
5549    @Override
5550    public int checkUidSignatures(int uid1, int uid2) {
5551        final int callingUid = Binder.getCallingUid();
5552        final int callingUserId = UserHandle.getUserId(callingUid);
5553        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5554        // Map to base uids.
5555        uid1 = UserHandle.getAppId(uid1);
5556        uid2 = UserHandle.getAppId(uid2);
5557        // reader
5558        synchronized (mPackages) {
5559            Signature[] s1;
5560            Signature[] s2;
5561            Object obj = mSettings.getUserIdLPr(uid1);
5562            if (obj != null) {
5563                if (obj instanceof SharedUserSetting) {
5564                    if (isCallerInstantApp) {
5565                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5566                    }
5567                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5568                } else if (obj instanceof PackageSetting) {
5569                    final PackageSetting ps = (PackageSetting) obj;
5570                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5571                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5572                    }
5573                    s1 = ps.signatures.mSigningDetails.signatures;
5574                } else {
5575                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5576                }
5577            } else {
5578                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5579            }
5580            obj = mSettings.getUserIdLPr(uid2);
5581            if (obj != null) {
5582                if (obj instanceof SharedUserSetting) {
5583                    if (isCallerInstantApp) {
5584                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5585                    }
5586                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5587                } else if (obj instanceof PackageSetting) {
5588                    final PackageSetting ps = (PackageSetting) obj;
5589                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5590                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5591                    }
5592                    s2 = ps.signatures.mSigningDetails.signatures;
5593                } else {
5594                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5595                }
5596            } else {
5597                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5598            }
5599            return compareSignatures(s1, s2);
5600        }
5601    }
5602
5603    @Override
5604    public boolean hasSigningCertificate(
5605            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5606
5607        synchronized (mPackages) {
5608            final PackageParser.Package p = mPackages.get(packageName);
5609            if (p == null || p.mExtras == null) {
5610                return false;
5611            }
5612            final int callingUid = Binder.getCallingUid();
5613            final int callingUserId = UserHandle.getUserId(callingUid);
5614            final PackageSetting ps = (PackageSetting) p.mExtras;
5615            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5616                return false;
5617            }
5618            switch (type) {
5619                case CERT_INPUT_RAW_X509:
5620                    return p.mSigningDetails.hasCertificate(certificate);
5621                case CERT_INPUT_SHA256:
5622                    return p.mSigningDetails.hasSha256Certificate(certificate);
5623                default:
5624                    return false;
5625            }
5626        }
5627    }
5628
5629    @Override
5630    public boolean hasUidSigningCertificate(
5631            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5632        final int callingUid = Binder.getCallingUid();
5633        final int callingUserId = UserHandle.getUserId(callingUid);
5634        // Map to base uids.
5635        uid = UserHandle.getAppId(uid);
5636        // reader
5637        synchronized (mPackages) {
5638            final PackageParser.SigningDetails signingDetails;
5639            final Object obj = mSettings.getUserIdLPr(uid);
5640            if (obj != null) {
5641                if (obj instanceof SharedUserSetting) {
5642                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5643                    if (isCallerInstantApp) {
5644                        return false;
5645                    }
5646                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5647                } else if (obj instanceof PackageSetting) {
5648                    final PackageSetting ps = (PackageSetting) obj;
5649                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5650                        return false;
5651                    }
5652                    signingDetails = ps.signatures.mSigningDetails;
5653                } else {
5654                    return false;
5655                }
5656            } else {
5657                return false;
5658            }
5659            switch (type) {
5660                case CERT_INPUT_RAW_X509:
5661                    return signingDetails.hasCertificate(certificate);
5662                case CERT_INPUT_SHA256:
5663                    return signingDetails.hasSha256Certificate(certificate);
5664                default:
5665                    return false;
5666            }
5667        }
5668    }
5669
5670    /**
5671     * This method should typically only be used when granting or revoking
5672     * permissions, since the app may immediately restart after this call.
5673     * <p>
5674     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5675     * guard your work against the app being relaunched.
5676     */
5677    private void killUid(int appId, int userId, String reason) {
5678        final long identity = Binder.clearCallingIdentity();
5679        try {
5680            IActivityManager am = ActivityManager.getService();
5681            if (am != null) {
5682                try {
5683                    am.killUid(appId, userId, reason);
5684                } catch (RemoteException e) {
5685                    /* ignore - same process */
5686                }
5687            }
5688        } finally {
5689            Binder.restoreCallingIdentity(identity);
5690        }
5691    }
5692
5693    /**
5694     * If the database version for this type of package (internal storage or
5695     * external storage) is less than the version where package signatures
5696     * were updated, return true.
5697     */
5698    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5699        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5700        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5701    }
5702
5703    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5704        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5705        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5706    }
5707
5708    @Override
5709    public List<String> getAllPackages() {
5710        final int callingUid = Binder.getCallingUid();
5711        final int callingUserId = UserHandle.getUserId(callingUid);
5712        synchronized (mPackages) {
5713            if (canViewInstantApps(callingUid, callingUserId)) {
5714                return new ArrayList<String>(mPackages.keySet());
5715            }
5716            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5717            final List<String> result = new ArrayList<>();
5718            if (instantAppPkgName != null) {
5719                // caller is an instant application; filter unexposed applications
5720                for (PackageParser.Package pkg : mPackages.values()) {
5721                    if (!pkg.visibleToInstantApps) {
5722                        continue;
5723                    }
5724                    result.add(pkg.packageName);
5725                }
5726            } else {
5727                // caller is a normal application; filter instant applications
5728                for (PackageParser.Package pkg : mPackages.values()) {
5729                    final PackageSetting ps =
5730                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5731                    if (ps != null
5732                            && ps.getInstantApp(callingUserId)
5733                            && !mInstantAppRegistry.isInstantAccessGranted(
5734                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5735                        continue;
5736                    }
5737                    result.add(pkg.packageName);
5738                }
5739            }
5740            return result;
5741        }
5742    }
5743
5744    @Override
5745    public String[] getPackagesForUid(int uid) {
5746        final int callingUid = Binder.getCallingUid();
5747        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5748        final int userId = UserHandle.getUserId(uid);
5749        uid = UserHandle.getAppId(uid);
5750        // reader
5751        synchronized (mPackages) {
5752            Object obj = mSettings.getUserIdLPr(uid);
5753            if (obj instanceof SharedUserSetting) {
5754                if (isCallerInstantApp) {
5755                    return null;
5756                }
5757                final SharedUserSetting sus = (SharedUserSetting) obj;
5758                final int N = sus.packages.size();
5759                String[] res = new String[N];
5760                final Iterator<PackageSetting> it = sus.packages.iterator();
5761                int i = 0;
5762                while (it.hasNext()) {
5763                    PackageSetting ps = it.next();
5764                    if (ps.getInstalled(userId)) {
5765                        res[i++] = ps.name;
5766                    } else {
5767                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5768                    }
5769                }
5770                return res;
5771            } else if (obj instanceof PackageSetting) {
5772                final PackageSetting ps = (PackageSetting) obj;
5773                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5774                    return new String[]{ps.name};
5775                }
5776            }
5777        }
5778        return null;
5779    }
5780
5781    @Override
5782    public String getNameForUid(int uid) {
5783        final int callingUid = Binder.getCallingUid();
5784        if (getInstantAppPackageName(callingUid) != null) {
5785            return null;
5786        }
5787        synchronized (mPackages) {
5788            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5789            if (obj instanceof SharedUserSetting) {
5790                final SharedUserSetting sus = (SharedUserSetting) obj;
5791                return sus.name + ":" + sus.userId;
5792            } else if (obj instanceof PackageSetting) {
5793                final PackageSetting ps = (PackageSetting) obj;
5794                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5795                    return null;
5796                }
5797                return ps.name;
5798            }
5799            return null;
5800        }
5801    }
5802
5803    @Override
5804    public String[] getNamesForUids(int[] uids) {
5805        if (uids == null || uids.length == 0) {
5806            return null;
5807        }
5808        final int callingUid = Binder.getCallingUid();
5809        if (getInstantAppPackageName(callingUid) != null) {
5810            return null;
5811        }
5812        final String[] names = new String[uids.length];
5813        synchronized (mPackages) {
5814            for (int i = uids.length - 1; i >= 0; i--) {
5815                final int uid = uids[i];
5816                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5817                if (obj instanceof SharedUserSetting) {
5818                    final SharedUserSetting sus = (SharedUserSetting) obj;
5819                    names[i] = "shared:" + sus.name;
5820                } else if (obj instanceof PackageSetting) {
5821                    final PackageSetting ps = (PackageSetting) obj;
5822                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5823                        names[i] = null;
5824                    } else {
5825                        names[i] = ps.name;
5826                    }
5827                } else {
5828                    names[i] = null;
5829                }
5830            }
5831        }
5832        return names;
5833    }
5834
5835    @Override
5836    public int getUidForSharedUser(String sharedUserName) {
5837        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5838            return -1;
5839        }
5840        if (sharedUserName == null) {
5841            return -1;
5842        }
5843        // reader
5844        synchronized (mPackages) {
5845            SharedUserSetting suid;
5846            try {
5847                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5848                if (suid != null) {
5849                    return suid.userId;
5850                }
5851            } catch (PackageManagerException ignore) {
5852                // can't happen, but, still need to catch it
5853            }
5854            return -1;
5855        }
5856    }
5857
5858    @Override
5859    public int getFlagsForUid(int uid) {
5860        final int callingUid = Binder.getCallingUid();
5861        if (getInstantAppPackageName(callingUid) != null) {
5862            return 0;
5863        }
5864        synchronized (mPackages) {
5865            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5866            if (obj instanceof SharedUserSetting) {
5867                final SharedUserSetting sus = (SharedUserSetting) obj;
5868                return sus.pkgFlags;
5869            } else if (obj instanceof PackageSetting) {
5870                final PackageSetting ps = (PackageSetting) obj;
5871                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5872                    return 0;
5873                }
5874                return ps.pkgFlags;
5875            }
5876        }
5877        return 0;
5878    }
5879
5880    @Override
5881    public int getPrivateFlagsForUid(int uid) {
5882        final int callingUid = Binder.getCallingUid();
5883        if (getInstantAppPackageName(callingUid) != null) {
5884            return 0;
5885        }
5886        synchronized (mPackages) {
5887            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5888            if (obj instanceof SharedUserSetting) {
5889                final SharedUserSetting sus = (SharedUserSetting) obj;
5890                return sus.pkgPrivateFlags;
5891            } else if (obj instanceof PackageSetting) {
5892                final PackageSetting ps = (PackageSetting) obj;
5893                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5894                    return 0;
5895                }
5896                return ps.pkgPrivateFlags;
5897            }
5898        }
5899        return 0;
5900    }
5901
5902    @Override
5903    public boolean isUidPrivileged(int uid) {
5904        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5905            return false;
5906        }
5907        uid = UserHandle.getAppId(uid);
5908        // reader
5909        synchronized (mPackages) {
5910            Object obj = mSettings.getUserIdLPr(uid);
5911            if (obj instanceof SharedUserSetting) {
5912                final SharedUserSetting sus = (SharedUserSetting) obj;
5913                final Iterator<PackageSetting> it = sus.packages.iterator();
5914                while (it.hasNext()) {
5915                    if (it.next().isPrivileged()) {
5916                        return true;
5917                    }
5918                }
5919            } else if (obj instanceof PackageSetting) {
5920                final PackageSetting ps = (PackageSetting) obj;
5921                return ps.isPrivileged();
5922            }
5923        }
5924        return false;
5925    }
5926
5927    @Override
5928    public String[] getAppOpPermissionPackages(String permName) {
5929        return mPermissionManager.getAppOpPermissionPackages(permName);
5930    }
5931
5932    @Override
5933    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5934            int flags, int userId) {
5935        return resolveIntentInternal(
5936                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5937    }
5938
5939    /**
5940     * Normally instant apps can only be resolved when they're visible to the caller.
5941     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5942     * since we need to allow the system to start any installed application.
5943     */
5944    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5945            int flags, int userId, boolean resolveForStart) {
5946        try {
5947            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5948
5949            if (!sUserManager.exists(userId)) return null;
5950            final int callingUid = Binder.getCallingUid();
5951            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5952            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5953                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5954
5955            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5956            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5957                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5958            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5959
5960            final ResolveInfo bestChoice =
5961                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5962            return bestChoice;
5963        } finally {
5964            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5965        }
5966    }
5967
5968    @Override
5969    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5970        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5971            throw new SecurityException(
5972                    "findPersistentPreferredActivity can only be run by the system");
5973        }
5974        if (!sUserManager.exists(userId)) {
5975            return null;
5976        }
5977        final int callingUid = Binder.getCallingUid();
5978        intent = updateIntentForResolve(intent);
5979        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5980        final int flags = updateFlagsForResolve(
5981                0, userId, intent, callingUid, false /*includeInstantApps*/);
5982        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5983                userId);
5984        synchronized (mPackages) {
5985            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5986                    userId);
5987        }
5988    }
5989
5990    @Override
5991    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5992            IntentFilter filter, int match, ComponentName activity) {
5993        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5994            return;
5995        }
5996        final int userId = UserHandle.getCallingUserId();
5997        if (DEBUG_PREFERRED) {
5998            Log.v(TAG, "setLastChosenActivity intent=" + intent
5999                + " resolvedType=" + resolvedType
6000                + " flags=" + flags
6001                + " filter=" + filter
6002                + " match=" + match
6003                + " activity=" + activity);
6004            filter.dump(new PrintStreamPrinter(System.out), "    ");
6005        }
6006        intent.setComponent(null);
6007        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6008                userId);
6009        // Find any earlier preferred or last chosen entries and nuke them
6010        findPreferredActivity(intent, resolvedType,
6011                flags, query, 0, false, true, false, userId);
6012        // Add the new activity as the last chosen for this filter
6013        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6014                "Setting last chosen");
6015    }
6016
6017    @Override
6018    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6019        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6020            return null;
6021        }
6022        final int userId = UserHandle.getCallingUserId();
6023        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6024        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6025                userId);
6026        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6027                false, false, false, userId);
6028    }
6029
6030    /**
6031     * Returns whether or not instant apps have been disabled remotely.
6032     */
6033    private boolean areWebInstantAppsDisabled() {
6034        return mWebInstantAppsDisabled;
6035    }
6036
6037    private boolean isInstantAppResolutionAllowed(
6038            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6039            boolean skipPackageCheck) {
6040        if (mInstantAppResolverConnection == null) {
6041            return false;
6042        }
6043        if (mInstantAppInstallerActivity == null) {
6044            return false;
6045        }
6046        if (intent.getComponent() != null) {
6047            return false;
6048        }
6049        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6050            return false;
6051        }
6052        if (!skipPackageCheck && intent.getPackage() != null) {
6053            return false;
6054        }
6055        if (!intent.isWebIntent()) {
6056            // for non web intents, we should not resolve externally if an app already exists to
6057            // handle it or if the caller didn't explicitly request it.
6058            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6059                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6060                return false;
6061            }
6062        } else {
6063            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6064                return false;
6065            } else if (areWebInstantAppsDisabled()) {
6066                return false;
6067            }
6068        }
6069        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6070        // Or if there's already an ephemeral app installed that handles the action
6071        synchronized (mPackages) {
6072            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6073            for (int n = 0; n < count; n++) {
6074                final ResolveInfo info = resolvedActivities.get(n);
6075                final String packageName = info.activityInfo.packageName;
6076                final PackageSetting ps = mSettings.mPackages.get(packageName);
6077                if (ps != null) {
6078                    // only check domain verification status if the app is not a browser
6079                    if (!info.handleAllWebDataURI) {
6080                        // Try to get the status from User settings first
6081                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6082                        final int status = (int) (packedStatus >> 32);
6083                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6084                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6085                            if (DEBUG_INSTANT) {
6086                                Slog.v(TAG, "DENY instant app;"
6087                                    + " pkg: " + packageName + ", status: " + status);
6088                            }
6089                            return false;
6090                        }
6091                    }
6092                    if (ps.getInstantApp(userId)) {
6093                        if (DEBUG_INSTANT) {
6094                            Slog.v(TAG, "DENY instant app installed;"
6095                                    + " pkg: " + packageName);
6096                        }
6097                        return false;
6098                    }
6099                }
6100            }
6101        }
6102        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6103        return true;
6104    }
6105
6106    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6107            Intent origIntent, String resolvedType, String callingPackage,
6108            Bundle verificationBundle, int userId) {
6109        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6110                new InstantAppRequest(responseObj, origIntent, resolvedType,
6111                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6112        mHandler.sendMessage(msg);
6113    }
6114
6115    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6116            int flags, List<ResolveInfo> query, int userId) {
6117        if (query != null) {
6118            final int N = query.size();
6119            if (N == 1) {
6120                return query.get(0);
6121            } else if (N > 1) {
6122                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6123                // If there is more than one activity with the same priority,
6124                // then let the user decide between them.
6125                ResolveInfo r0 = query.get(0);
6126                ResolveInfo r1 = query.get(1);
6127                if (DEBUG_INTENT_MATCHING || debug) {
6128                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6129                            + r1.activityInfo.name + "=" + r1.priority);
6130                }
6131                // If the first activity has a higher priority, or a different
6132                // default, then it is always desirable to pick it.
6133                if (r0.priority != r1.priority
6134                        || r0.preferredOrder != r1.preferredOrder
6135                        || r0.isDefault != r1.isDefault) {
6136                    return query.get(0);
6137                }
6138                // If we have saved a preference for a preferred activity for
6139                // this Intent, use that.
6140                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6141                        flags, query, r0.priority, true, false, debug, userId);
6142                if (ri != null) {
6143                    return ri;
6144                }
6145                // If we have an ephemeral app, use it
6146                for (int i = 0; i < N; i++) {
6147                    ri = query.get(i);
6148                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6149                        final String packageName = ri.activityInfo.packageName;
6150                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6151                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6152                        final int status = (int)(packedStatus >> 32);
6153                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6154                            return ri;
6155                        }
6156                    }
6157                }
6158                ri = new ResolveInfo(mResolveInfo);
6159                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6160                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6161                // If all of the options come from the same package, show the application's
6162                // label and icon instead of the generic resolver's.
6163                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6164                // and then throw away the ResolveInfo itself, meaning that the caller loses
6165                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6166                // a fallback for this case; we only set the target package's resources on
6167                // the ResolveInfo, not the ActivityInfo.
6168                final String intentPackage = intent.getPackage();
6169                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6170                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6171                    ri.resolvePackageName = intentPackage;
6172                    if (userNeedsBadging(userId)) {
6173                        ri.noResourceId = true;
6174                    } else {
6175                        ri.icon = appi.icon;
6176                    }
6177                    ri.iconResourceId = appi.icon;
6178                    ri.labelRes = appi.labelRes;
6179                }
6180                ri.activityInfo.applicationInfo = new ApplicationInfo(
6181                        ri.activityInfo.applicationInfo);
6182                if (userId != 0) {
6183                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6184                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6185                }
6186                // Make sure that the resolver is displayable in car mode
6187                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6188                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6189                return ri;
6190            }
6191        }
6192        return null;
6193    }
6194
6195    /**
6196     * Return true if the given list is not empty and all of its contents have
6197     * an activityInfo with the given package name.
6198     */
6199    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6200        if (ArrayUtils.isEmpty(list)) {
6201            return false;
6202        }
6203        for (int i = 0, N = list.size(); i < N; i++) {
6204            final ResolveInfo ri = list.get(i);
6205            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6206            if (ai == null || !packageName.equals(ai.packageName)) {
6207                return false;
6208            }
6209        }
6210        return true;
6211    }
6212
6213    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6214            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6215        final int N = query.size();
6216        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6217                .get(userId);
6218        // Get the list of persistent preferred activities that handle the intent
6219        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6220        List<PersistentPreferredActivity> pprefs = ppir != null
6221                ? ppir.queryIntent(intent, resolvedType,
6222                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6223                        userId)
6224                : null;
6225        if (pprefs != null && pprefs.size() > 0) {
6226            final int M = pprefs.size();
6227            for (int i=0; i<M; i++) {
6228                final PersistentPreferredActivity ppa = pprefs.get(i);
6229                if (DEBUG_PREFERRED || debug) {
6230                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6231                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6232                            + "\n  component=" + ppa.mComponent);
6233                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6234                }
6235                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6236                        flags | MATCH_DISABLED_COMPONENTS, userId);
6237                if (DEBUG_PREFERRED || debug) {
6238                    Slog.v(TAG, "Found persistent preferred activity:");
6239                    if (ai != null) {
6240                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6241                    } else {
6242                        Slog.v(TAG, "  null");
6243                    }
6244                }
6245                if (ai == null) {
6246                    // This previously registered persistent preferred activity
6247                    // component is no longer known. Ignore it and do NOT remove it.
6248                    continue;
6249                }
6250                for (int j=0; j<N; j++) {
6251                    final ResolveInfo ri = query.get(j);
6252                    if (!ri.activityInfo.applicationInfo.packageName
6253                            .equals(ai.applicationInfo.packageName)) {
6254                        continue;
6255                    }
6256                    if (!ri.activityInfo.name.equals(ai.name)) {
6257                        continue;
6258                    }
6259                    //  Found a persistent preference that can handle the intent.
6260                    if (DEBUG_PREFERRED || debug) {
6261                        Slog.v(TAG, "Returning persistent preferred activity: " +
6262                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6263                    }
6264                    return ri;
6265                }
6266            }
6267        }
6268        return null;
6269    }
6270
6271    // TODO: handle preferred activities missing while user has amnesia
6272    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6273            List<ResolveInfo> query, int priority, boolean always,
6274            boolean removeMatches, boolean debug, int userId) {
6275        if (!sUserManager.exists(userId)) return null;
6276        final int callingUid = Binder.getCallingUid();
6277        flags = updateFlagsForResolve(
6278                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6279        intent = updateIntentForResolve(intent);
6280        // writer
6281        synchronized (mPackages) {
6282            // Try to find a matching persistent preferred activity.
6283            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6284                    debug, userId);
6285
6286            // If a persistent preferred activity matched, use it.
6287            if (pri != null) {
6288                return pri;
6289            }
6290
6291            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6292            // Get the list of preferred activities that handle the intent
6293            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6294            List<PreferredActivity> prefs = pir != null
6295                    ? pir.queryIntent(intent, resolvedType,
6296                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6297                            userId)
6298                    : null;
6299            if (prefs != null && prefs.size() > 0) {
6300                boolean changed = false;
6301                try {
6302                    // First figure out how good the original match set is.
6303                    // We will only allow preferred activities that came
6304                    // from the same match quality.
6305                    int match = 0;
6306
6307                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6308
6309                    final int N = query.size();
6310                    for (int j=0; j<N; j++) {
6311                        final ResolveInfo ri = query.get(j);
6312                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6313                                + ": 0x" + Integer.toHexString(match));
6314                        if (ri.match > match) {
6315                            match = ri.match;
6316                        }
6317                    }
6318
6319                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6320                            + Integer.toHexString(match));
6321
6322                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6323                    final int M = prefs.size();
6324                    for (int i=0; i<M; i++) {
6325                        final PreferredActivity pa = prefs.get(i);
6326                        if (DEBUG_PREFERRED || debug) {
6327                            Slog.v(TAG, "Checking PreferredActivity ds="
6328                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6329                                    + "\n  component=" + pa.mPref.mComponent);
6330                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6331                        }
6332                        if (pa.mPref.mMatch != match) {
6333                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6334                                    + Integer.toHexString(pa.mPref.mMatch));
6335                            continue;
6336                        }
6337                        // If it's not an "always" type preferred activity and that's what we're
6338                        // looking for, skip it.
6339                        if (always && !pa.mPref.mAlways) {
6340                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6341                            continue;
6342                        }
6343                        final ActivityInfo ai = getActivityInfo(
6344                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6345                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6346                                userId);
6347                        if (DEBUG_PREFERRED || debug) {
6348                            Slog.v(TAG, "Found preferred activity:");
6349                            if (ai != null) {
6350                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6351                            } else {
6352                                Slog.v(TAG, "  null");
6353                            }
6354                        }
6355                        if (ai == null) {
6356                            // This previously registered preferred activity
6357                            // component is no longer known.  Most likely an update
6358                            // to the app was installed and in the new version this
6359                            // component no longer exists.  Clean it up by removing
6360                            // it from the preferred activities list, and skip it.
6361                            Slog.w(TAG, "Removing dangling preferred activity: "
6362                                    + pa.mPref.mComponent);
6363                            pir.removeFilter(pa);
6364                            changed = true;
6365                            continue;
6366                        }
6367                        for (int j=0; j<N; j++) {
6368                            final ResolveInfo ri = query.get(j);
6369                            if (!ri.activityInfo.applicationInfo.packageName
6370                                    .equals(ai.applicationInfo.packageName)) {
6371                                continue;
6372                            }
6373                            if (!ri.activityInfo.name.equals(ai.name)) {
6374                                continue;
6375                            }
6376
6377                            if (removeMatches) {
6378                                pir.removeFilter(pa);
6379                                changed = true;
6380                                if (DEBUG_PREFERRED) {
6381                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6382                                }
6383                                break;
6384                            }
6385
6386                            // Okay we found a previously set preferred or last chosen app.
6387                            // If the result set is different from when this
6388                            // was created, and is not a subset of the preferred set, we need to
6389                            // clear it and re-ask the user their preference, if we're looking for
6390                            // an "always" type entry.
6391                            if (always && !pa.mPref.sameSet(query)) {
6392                                if (pa.mPref.isSuperset(query)) {
6393                                    // some components of the set are no longer present in
6394                                    // the query, but the preferred activity can still be reused
6395                                    if (DEBUG_PREFERRED) {
6396                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6397                                                + " still valid as only non-preferred components"
6398                                                + " were removed for " + intent + " type "
6399                                                + resolvedType);
6400                                    }
6401                                    // remove obsolete components and re-add the up-to-date filter
6402                                    PreferredActivity freshPa = new PreferredActivity(pa,
6403                                            pa.mPref.mMatch,
6404                                            pa.mPref.discardObsoleteComponents(query),
6405                                            pa.mPref.mComponent,
6406                                            pa.mPref.mAlways);
6407                                    pir.removeFilter(pa);
6408                                    pir.addFilter(freshPa);
6409                                    changed = true;
6410                                } else {
6411                                    Slog.i(TAG,
6412                                            "Result set changed, dropping preferred activity for "
6413                                                    + intent + " type " + resolvedType);
6414                                    if (DEBUG_PREFERRED) {
6415                                        Slog.v(TAG, "Removing preferred activity since set changed "
6416                                                + pa.mPref.mComponent);
6417                                    }
6418                                    pir.removeFilter(pa);
6419                                    // Re-add the filter as a "last chosen" entry (!always)
6420                                    PreferredActivity lastChosen = new PreferredActivity(
6421                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6422                                    pir.addFilter(lastChosen);
6423                                    changed = true;
6424                                    return null;
6425                                }
6426                            }
6427
6428                            // Yay! Either the set matched or we're looking for the last chosen
6429                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6430                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6431                            return ri;
6432                        }
6433                    }
6434                } finally {
6435                    if (changed) {
6436                        if (DEBUG_PREFERRED) {
6437                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6438                        }
6439                        scheduleWritePackageRestrictionsLocked(userId);
6440                    }
6441                }
6442            }
6443        }
6444        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6445        return null;
6446    }
6447
6448    /*
6449     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6450     */
6451    @Override
6452    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6453            int targetUserId) {
6454        mContext.enforceCallingOrSelfPermission(
6455                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6456        List<CrossProfileIntentFilter> matches =
6457                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6458        if (matches != null) {
6459            int size = matches.size();
6460            for (int i = 0; i < size; i++) {
6461                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6462            }
6463        }
6464        if (intent.hasWebURI()) {
6465            // cross-profile app linking works only towards the parent.
6466            final int callingUid = Binder.getCallingUid();
6467            final UserInfo parent = getProfileParent(sourceUserId);
6468            synchronized(mPackages) {
6469                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6470                        false /*includeInstantApps*/);
6471                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6472                        intent, resolvedType, flags, sourceUserId, parent.id);
6473                return xpDomainInfo != null;
6474            }
6475        }
6476        return false;
6477    }
6478
6479    private UserInfo getProfileParent(int userId) {
6480        final long identity = Binder.clearCallingIdentity();
6481        try {
6482            return sUserManager.getProfileParent(userId);
6483        } finally {
6484            Binder.restoreCallingIdentity(identity);
6485        }
6486    }
6487
6488    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6489            String resolvedType, int userId) {
6490        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6491        if (resolver != null) {
6492            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6493        }
6494        return null;
6495    }
6496
6497    @Override
6498    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6499            String resolvedType, int flags, int userId) {
6500        try {
6501            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6502
6503            return new ParceledListSlice<>(
6504                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6505        } finally {
6506            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6507        }
6508    }
6509
6510    /**
6511     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6512     * instant, returns {@code null}.
6513     */
6514    private String getInstantAppPackageName(int callingUid) {
6515        synchronized (mPackages) {
6516            // If the caller is an isolated app use the owner's uid for the lookup.
6517            if (Process.isIsolated(callingUid)) {
6518                callingUid = mIsolatedOwners.get(callingUid);
6519            }
6520            final int appId = UserHandle.getAppId(callingUid);
6521            final Object obj = mSettings.getUserIdLPr(appId);
6522            if (obj instanceof PackageSetting) {
6523                final PackageSetting ps = (PackageSetting) obj;
6524                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6525                return isInstantApp ? ps.pkg.packageName : null;
6526            }
6527        }
6528        return null;
6529    }
6530
6531    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6532            String resolvedType, int flags, int userId) {
6533        return queryIntentActivitiesInternal(
6534                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6535                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6536    }
6537
6538    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6539            String resolvedType, int flags, int filterCallingUid, int userId,
6540            boolean resolveForStart, boolean allowDynamicSplits) {
6541        if (!sUserManager.exists(userId)) return Collections.emptyList();
6542        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6543        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6544                false /* requireFullPermission */, false /* checkShell */,
6545                "query intent activities");
6546        final String pkgName = intent.getPackage();
6547        ComponentName comp = intent.getComponent();
6548        if (comp == null) {
6549            if (intent.getSelector() != null) {
6550                intent = intent.getSelector();
6551                comp = intent.getComponent();
6552            }
6553        }
6554
6555        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6556                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6557        if (comp != null) {
6558            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6559            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6560            if (ai != null) {
6561                // When specifying an explicit component, we prevent the activity from being
6562                // used when either 1) the calling package is normal and the activity is within
6563                // an ephemeral application or 2) the calling package is ephemeral and the
6564                // activity is not visible to ephemeral applications.
6565                final boolean matchInstantApp =
6566                        (flags & PackageManager.MATCH_INSTANT) != 0;
6567                final boolean matchVisibleToInstantAppOnly =
6568                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6569                final boolean matchExplicitlyVisibleOnly =
6570                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6571                final boolean isCallerInstantApp =
6572                        instantAppPkgName != null;
6573                final boolean isTargetSameInstantApp =
6574                        comp.getPackageName().equals(instantAppPkgName);
6575                final boolean isTargetInstantApp =
6576                        (ai.applicationInfo.privateFlags
6577                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6578                final boolean isTargetVisibleToInstantApp =
6579                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6580                final boolean isTargetExplicitlyVisibleToInstantApp =
6581                        isTargetVisibleToInstantApp
6582                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6583                final boolean isTargetHiddenFromInstantApp =
6584                        !isTargetVisibleToInstantApp
6585                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6586                final boolean blockResolution =
6587                        !isTargetSameInstantApp
6588                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6589                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6590                                        && isTargetHiddenFromInstantApp));
6591                if (!blockResolution) {
6592                    final ResolveInfo ri = new ResolveInfo();
6593                    ri.activityInfo = ai;
6594                    list.add(ri);
6595                }
6596            }
6597            return applyPostResolutionFilter(
6598                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6599        }
6600
6601        // reader
6602        boolean sortResult = false;
6603        boolean addInstant = false;
6604        List<ResolveInfo> result;
6605        synchronized (mPackages) {
6606            if (pkgName == null) {
6607                List<CrossProfileIntentFilter> matchingFilters =
6608                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6609                // Check for results that need to skip the current profile.
6610                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6611                        resolvedType, flags, userId);
6612                if (xpResolveInfo != null) {
6613                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6614                    xpResult.add(xpResolveInfo);
6615                    return applyPostResolutionFilter(
6616                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6617                            allowDynamicSplits, filterCallingUid, userId, intent);
6618                }
6619
6620                // Check for results in the current profile.
6621                result = filterIfNotSystemUser(mActivities.queryIntent(
6622                        intent, resolvedType, flags, userId), userId);
6623                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6624                        false /*skipPackageCheck*/);
6625                // Check for cross profile results.
6626                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6627                xpResolveInfo = queryCrossProfileIntents(
6628                        matchingFilters, intent, resolvedType, flags, userId,
6629                        hasNonNegativePriorityResult);
6630                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6631                    boolean isVisibleToUser = filterIfNotSystemUser(
6632                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6633                    if (isVisibleToUser) {
6634                        result.add(xpResolveInfo);
6635                        sortResult = true;
6636                    }
6637                }
6638                if (intent.hasWebURI()) {
6639                    CrossProfileDomainInfo xpDomainInfo = null;
6640                    final UserInfo parent = getProfileParent(userId);
6641                    if (parent != null) {
6642                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6643                                flags, userId, parent.id);
6644                    }
6645                    if (xpDomainInfo != null) {
6646                        if (xpResolveInfo != null) {
6647                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6648                            // in the result.
6649                            result.remove(xpResolveInfo);
6650                        }
6651                        if (result.size() == 0 && !addInstant) {
6652                            // No result in current profile, but found candidate in parent user.
6653                            // And we are not going to add emphemeral app, so we can return the
6654                            // result straight away.
6655                            result.add(xpDomainInfo.resolveInfo);
6656                            return applyPostResolutionFilter(result, instantAppPkgName,
6657                                    allowDynamicSplits, filterCallingUid, userId, intent);
6658                        }
6659                    } else if (result.size() <= 1 && !addInstant) {
6660                        // No result in parent user and <= 1 result in current profile, and we
6661                        // are not going to add emphemeral app, so we can return the result without
6662                        // further processing.
6663                        return applyPostResolutionFilter(result, instantAppPkgName,
6664                                allowDynamicSplits, filterCallingUid, userId, intent);
6665                    }
6666                    // We have more than one candidate (combining results from current and parent
6667                    // profile), so we need filtering and sorting.
6668                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6669                            intent, flags, result, xpDomainInfo, userId);
6670                    sortResult = true;
6671                }
6672            } else {
6673                final PackageParser.Package pkg = mPackages.get(pkgName);
6674                result = null;
6675                if (pkg != null) {
6676                    result = filterIfNotSystemUser(
6677                            mActivities.queryIntentForPackage(
6678                                    intent, resolvedType, flags, pkg.activities, userId),
6679                            userId);
6680                }
6681                if (result == null || result.size() == 0) {
6682                    // the caller wants to resolve for a particular package; however, there
6683                    // were no installed results, so, try to find an ephemeral result
6684                    addInstant = isInstantAppResolutionAllowed(
6685                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6686                    if (result == null) {
6687                        result = new ArrayList<>();
6688                    }
6689                }
6690            }
6691        }
6692        if (addInstant) {
6693            result = maybeAddInstantAppInstaller(
6694                    result, intent, resolvedType, flags, userId, resolveForStart);
6695        }
6696        if (sortResult) {
6697            Collections.sort(result, mResolvePrioritySorter);
6698        }
6699        return applyPostResolutionFilter(
6700                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6701    }
6702
6703    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6704            String resolvedType, int flags, int userId, boolean resolveForStart) {
6705        // first, check to see if we've got an instant app already installed
6706        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6707        ResolveInfo localInstantApp = null;
6708        boolean blockResolution = false;
6709        if (!alreadyResolvedLocally) {
6710            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6711                    flags
6712                        | PackageManager.GET_RESOLVED_FILTER
6713                        | PackageManager.MATCH_INSTANT
6714                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6715                    userId);
6716            for (int i = instantApps.size() - 1; i >= 0; --i) {
6717                final ResolveInfo info = instantApps.get(i);
6718                final String packageName = info.activityInfo.packageName;
6719                final PackageSetting ps = mSettings.mPackages.get(packageName);
6720                if (ps.getInstantApp(userId)) {
6721                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6722                    final int status = (int)(packedStatus >> 32);
6723                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6724                        // there's a local instant application installed, but, the user has
6725                        // chosen to never use it; skip resolution and don't acknowledge
6726                        // an instant application is even available
6727                        if (DEBUG_INSTANT) {
6728                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6729                        }
6730                        blockResolution = true;
6731                        break;
6732                    } else {
6733                        // we have a locally installed instant application; skip resolution
6734                        // but acknowledge there's an instant application available
6735                        if (DEBUG_INSTANT) {
6736                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6737                        }
6738                        localInstantApp = info;
6739                        break;
6740                    }
6741                }
6742            }
6743        }
6744        // no app installed, let's see if one's available
6745        AuxiliaryResolveInfo auxiliaryResponse = null;
6746        if (!blockResolution) {
6747            if (localInstantApp == null) {
6748                // we don't have an instant app locally, resolve externally
6749                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6750                final InstantAppRequest requestObject = new InstantAppRequest(
6751                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6752                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6753                        resolveForStart);
6754                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6755                        mInstantAppResolverConnection, requestObject);
6756                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6757            } else {
6758                // we have an instant application locally, but, we can't admit that since
6759                // callers shouldn't be able to determine prior browsing. create a dummy
6760                // auxiliary response so the downstream code behaves as if there's an
6761                // instant application available externally. when it comes time to start
6762                // the instant application, we'll do the right thing.
6763                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6764                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6765                                        ai.packageName, ai.versionCode, null /* splitName */);
6766            }
6767        }
6768        if (intent.isWebIntent() && auxiliaryResponse == null) {
6769            return result;
6770        }
6771        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6772        if (ps == null
6773                || ps.getUserState().get(userId) == null
6774                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6775            return result;
6776        }
6777        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6778        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6779                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6780        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6781                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6782        // add a non-generic filter
6783        ephemeralInstaller.filter = new IntentFilter();
6784        if (intent.getAction() != null) {
6785            ephemeralInstaller.filter.addAction(intent.getAction());
6786        }
6787        if (intent.getData() != null && intent.getData().getPath() != null) {
6788            ephemeralInstaller.filter.addDataPath(
6789                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6790        }
6791        ephemeralInstaller.isInstantAppAvailable = true;
6792        // make sure this resolver is the default
6793        ephemeralInstaller.isDefault = true;
6794        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6795        if (DEBUG_INSTANT) {
6796            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6797        }
6798
6799        result.add(ephemeralInstaller);
6800        return result;
6801    }
6802
6803    private static class CrossProfileDomainInfo {
6804        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6805        ResolveInfo resolveInfo;
6806        /* Best domain verification status of the activities found in the other profile */
6807        int bestDomainVerificationStatus;
6808    }
6809
6810    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6811            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6812        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6813                sourceUserId)) {
6814            return null;
6815        }
6816        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6817                resolvedType, flags, parentUserId);
6818
6819        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6820            return null;
6821        }
6822        CrossProfileDomainInfo result = null;
6823        int size = resultTargetUser.size();
6824        for (int i = 0; i < size; i++) {
6825            ResolveInfo riTargetUser = resultTargetUser.get(i);
6826            // Intent filter verification is only for filters that specify a host. So don't return
6827            // those that handle all web uris.
6828            if (riTargetUser.handleAllWebDataURI) {
6829                continue;
6830            }
6831            String packageName = riTargetUser.activityInfo.packageName;
6832            PackageSetting ps = mSettings.mPackages.get(packageName);
6833            if (ps == null) {
6834                continue;
6835            }
6836            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6837            int status = (int)(verificationState >> 32);
6838            if (result == null) {
6839                result = new CrossProfileDomainInfo();
6840                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6841                        sourceUserId, parentUserId);
6842                result.bestDomainVerificationStatus = status;
6843            } else {
6844                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6845                        result.bestDomainVerificationStatus);
6846            }
6847        }
6848        // Don't consider matches with status NEVER across profiles.
6849        if (result != null && result.bestDomainVerificationStatus
6850                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6851            return null;
6852        }
6853        return result;
6854    }
6855
6856    /**
6857     * Verification statuses are ordered from the worse to the best, except for
6858     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6859     */
6860    private int bestDomainVerificationStatus(int status1, int status2) {
6861        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6862            return status2;
6863        }
6864        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6865            return status1;
6866        }
6867        return (int) MathUtils.max(status1, status2);
6868    }
6869
6870    private boolean isUserEnabled(int userId) {
6871        long callingId = Binder.clearCallingIdentity();
6872        try {
6873            UserInfo userInfo = sUserManager.getUserInfo(userId);
6874            return userInfo != null && userInfo.isEnabled();
6875        } finally {
6876            Binder.restoreCallingIdentity(callingId);
6877        }
6878    }
6879
6880    /**
6881     * Filter out activities with systemUserOnly flag set, when current user is not System.
6882     *
6883     * @return filtered list
6884     */
6885    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6886        if (userId == UserHandle.USER_SYSTEM) {
6887            return resolveInfos;
6888        }
6889        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6890            ResolveInfo info = resolveInfos.get(i);
6891            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6892                resolveInfos.remove(i);
6893            }
6894        }
6895        return resolveInfos;
6896    }
6897
6898    /**
6899     * Filters out ephemeral activities.
6900     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6901     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6902     *
6903     * @param resolveInfos The pre-filtered list of resolved activities
6904     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6905     *          is performed.
6906     * @param intent
6907     * @return A filtered list of resolved activities.
6908     */
6909    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6910            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6911            Intent intent) {
6912        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6913        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6914            final ResolveInfo info = resolveInfos.get(i);
6915            // remove locally resolved instant app web results when disabled
6916            if (info.isInstantAppAvailable && blockInstant) {
6917                resolveInfos.remove(i);
6918                continue;
6919            }
6920            // allow activities that are defined in the provided package
6921            if (allowDynamicSplits
6922                    && info.activityInfo != null
6923                    && info.activityInfo.splitName != null
6924                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6925                            info.activityInfo.splitName)) {
6926                if (mInstantAppInstallerActivity == null) {
6927                    if (DEBUG_INSTALL) {
6928                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6929                    }
6930                    resolveInfos.remove(i);
6931                    continue;
6932                }
6933                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6934                    resolveInfos.remove(i);
6935                    continue;
6936                }
6937                // requested activity is defined in a split that hasn't been installed yet.
6938                // add the installer to the resolve list
6939                if (DEBUG_INSTALL) {
6940                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6941                }
6942                final ResolveInfo installerInfo = new ResolveInfo(
6943                        mInstantAppInstallerInfo);
6944                final ComponentName installFailureActivity = findInstallFailureActivity(
6945                        info.activityInfo.packageName,  filterCallingUid, userId);
6946                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6947                        installFailureActivity,
6948                        info.activityInfo.packageName,
6949                        info.activityInfo.applicationInfo.versionCode,
6950                        info.activityInfo.splitName);
6951                // add a non-generic filter
6952                installerInfo.filter = new IntentFilter();
6953
6954                // This resolve info may appear in the chooser UI, so let us make it
6955                // look as the one it replaces as far as the user is concerned which
6956                // requires loading the correct label and icon for the resolve info.
6957                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6958                installerInfo.labelRes = info.resolveLabelResId();
6959                installerInfo.icon = info.resolveIconResId();
6960                installerInfo.isInstantAppAvailable = true;
6961                resolveInfos.set(i, installerInfo);
6962                continue;
6963            }
6964            // caller is a full app, don't need to apply any other filtering
6965            if (ephemeralPkgName == null) {
6966                continue;
6967            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6968                // caller is same app; don't need to apply any other filtering
6969                continue;
6970            }
6971            // allow activities that have been explicitly exposed to ephemeral apps
6972            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6973            if (!isEphemeralApp
6974                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6975                continue;
6976            }
6977            resolveInfos.remove(i);
6978        }
6979        return resolveInfos;
6980    }
6981
6982    /**
6983     * Returns the activity component that can handle install failures.
6984     * <p>By default, the instant application installer handles failures. However, an
6985     * application may want to handle failures on its own. Applications do this by
6986     * creating an activity with an intent filter that handles the action
6987     * {@link Intent#ACTION_INSTALL_FAILURE}.
6988     */
6989    private @Nullable ComponentName findInstallFailureActivity(
6990            String packageName, int filterCallingUid, int userId) {
6991        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6992        failureActivityIntent.setPackage(packageName);
6993        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6994        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6995                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6996                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6997        final int NR = result.size();
6998        if (NR > 0) {
6999            for (int i = 0; i < NR; i++) {
7000                final ResolveInfo info = result.get(i);
7001                if (info.activityInfo.splitName != null) {
7002                    continue;
7003                }
7004                return new ComponentName(packageName, info.activityInfo.name);
7005            }
7006        }
7007        return null;
7008    }
7009
7010    /**
7011     * @param resolveInfos list of resolve infos in descending priority order
7012     * @return if the list contains a resolve info with non-negative priority
7013     */
7014    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7015        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7016    }
7017
7018    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7019            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7020            int userId) {
7021        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7022
7023        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7024            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7025                    candidates.size());
7026        }
7027
7028        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7029        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7030        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7031        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7032        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7033        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7034
7035        synchronized (mPackages) {
7036            final int count = candidates.size();
7037            // First, try to use linked apps. Partition the candidates into four lists:
7038            // one for the final results, one for the "do not use ever", one for "undefined status"
7039            // and finally one for "browser app type".
7040            for (int n=0; n<count; n++) {
7041                ResolveInfo info = candidates.get(n);
7042                String packageName = info.activityInfo.packageName;
7043                PackageSetting ps = mSettings.mPackages.get(packageName);
7044                if (ps != null) {
7045                    // Add to the special match all list (Browser use case)
7046                    if (info.handleAllWebDataURI) {
7047                        matchAllList.add(info);
7048                        continue;
7049                    }
7050                    // Try to get the status from User settings first
7051                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7052                    int status = (int)(packedStatus >> 32);
7053                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7054                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7055                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7056                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7057                                    + " : linkgen=" + linkGeneration);
7058                        }
7059                        // Use link-enabled generation as preferredOrder, i.e.
7060                        // prefer newly-enabled over earlier-enabled.
7061                        info.preferredOrder = linkGeneration;
7062                        alwaysList.add(info);
7063                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7064                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7065                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7066                        }
7067                        neverList.add(info);
7068                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7069                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7070                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7071                        }
7072                        alwaysAskList.add(info);
7073                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7074                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7075                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7076                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7077                        }
7078                        undefinedList.add(info);
7079                    }
7080                }
7081            }
7082
7083            // We'll want to include browser possibilities in a few cases
7084            boolean includeBrowser = false;
7085
7086            // First try to add the "always" resolution(s) for the current user, if any
7087            if (alwaysList.size() > 0) {
7088                result.addAll(alwaysList);
7089            } else {
7090                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7091                result.addAll(undefinedList);
7092                // Maybe add one for the other profile.
7093                if (xpDomainInfo != null && (
7094                        xpDomainInfo.bestDomainVerificationStatus
7095                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7096                    result.add(xpDomainInfo.resolveInfo);
7097                }
7098                includeBrowser = true;
7099            }
7100
7101            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7102            // If there were 'always' entries their preferred order has been set, so we also
7103            // back that off to make the alternatives equivalent
7104            if (alwaysAskList.size() > 0) {
7105                for (ResolveInfo i : result) {
7106                    i.preferredOrder = 0;
7107                }
7108                result.addAll(alwaysAskList);
7109                includeBrowser = true;
7110            }
7111
7112            if (includeBrowser) {
7113                // Also add browsers (all of them or only the default one)
7114                if (DEBUG_DOMAIN_VERIFICATION) {
7115                    Slog.v(TAG, "   ...including browsers in candidate set");
7116                }
7117                if ((matchFlags & MATCH_ALL) != 0) {
7118                    result.addAll(matchAllList);
7119                } else {
7120                    // Browser/generic handling case.  If there's a default browser, go straight
7121                    // to that (but only if there is no other higher-priority match).
7122                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7123                    int maxMatchPrio = 0;
7124                    ResolveInfo defaultBrowserMatch = null;
7125                    final int numCandidates = matchAllList.size();
7126                    for (int n = 0; n < numCandidates; n++) {
7127                        ResolveInfo info = matchAllList.get(n);
7128                        // track the highest overall match priority...
7129                        if (info.priority > maxMatchPrio) {
7130                            maxMatchPrio = info.priority;
7131                        }
7132                        // ...and the highest-priority default browser match
7133                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7134                            if (defaultBrowserMatch == null
7135                                    || (defaultBrowserMatch.priority < info.priority)) {
7136                                if (debug) {
7137                                    Slog.v(TAG, "Considering default browser match " + info);
7138                                }
7139                                defaultBrowserMatch = info;
7140                            }
7141                        }
7142                    }
7143                    if (defaultBrowserMatch != null
7144                            && defaultBrowserMatch.priority >= maxMatchPrio
7145                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7146                    {
7147                        if (debug) {
7148                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7149                        }
7150                        result.add(defaultBrowserMatch);
7151                    } else {
7152                        result.addAll(matchAllList);
7153                    }
7154                }
7155
7156                // If there is nothing selected, add all candidates and remove the ones that the user
7157                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7158                if (result.size() == 0) {
7159                    result.addAll(candidates);
7160                    result.removeAll(neverList);
7161                }
7162            }
7163        }
7164        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7165            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7166                    result.size());
7167            for (ResolveInfo info : result) {
7168                Slog.v(TAG, "  + " + info.activityInfo);
7169            }
7170        }
7171        return result;
7172    }
7173
7174    // Returns a packed value as a long:
7175    //
7176    // high 'int'-sized word: link status: undefined/ask/never/always.
7177    // low 'int'-sized word: relative priority among 'always' results.
7178    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7179        long result = ps.getDomainVerificationStatusForUser(userId);
7180        // if none available, get the master status
7181        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7182            if (ps.getIntentFilterVerificationInfo() != null) {
7183                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7184            }
7185        }
7186        return result;
7187    }
7188
7189    private ResolveInfo querySkipCurrentProfileIntents(
7190            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7191            int flags, int sourceUserId) {
7192        if (matchingFilters != null) {
7193            int size = matchingFilters.size();
7194            for (int i = 0; i < size; i ++) {
7195                CrossProfileIntentFilter filter = matchingFilters.get(i);
7196                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7197                    // Checking if there are activities in the target user that can handle the
7198                    // intent.
7199                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7200                            resolvedType, flags, sourceUserId);
7201                    if (resolveInfo != null) {
7202                        return resolveInfo;
7203                    }
7204                }
7205            }
7206        }
7207        return null;
7208    }
7209
7210    // Return matching ResolveInfo in target user if any.
7211    private ResolveInfo queryCrossProfileIntents(
7212            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7213            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7214        if (matchingFilters != null) {
7215            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7216            // match the same intent. For performance reasons, it is better not to
7217            // run queryIntent twice for the same userId
7218            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7219            int size = matchingFilters.size();
7220            for (int i = 0; i < size; i++) {
7221                CrossProfileIntentFilter filter = matchingFilters.get(i);
7222                int targetUserId = filter.getTargetUserId();
7223                boolean skipCurrentProfile =
7224                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7225                boolean skipCurrentProfileIfNoMatchFound =
7226                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7227                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7228                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7229                    // Checking if there are activities in the target user that can handle the
7230                    // intent.
7231                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7232                            resolvedType, flags, sourceUserId);
7233                    if (resolveInfo != null) return resolveInfo;
7234                    alreadyTriedUserIds.put(targetUserId, true);
7235                }
7236            }
7237        }
7238        return null;
7239    }
7240
7241    /**
7242     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7243     * will forward the intent to the filter's target user.
7244     * Otherwise, returns null.
7245     */
7246    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7247            String resolvedType, int flags, int sourceUserId) {
7248        int targetUserId = filter.getTargetUserId();
7249        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7250                resolvedType, flags, targetUserId);
7251        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7252            // If all the matches in the target profile are suspended, return null.
7253            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7254                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7255                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7256                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7257                            targetUserId);
7258                }
7259            }
7260        }
7261        return null;
7262    }
7263
7264    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7265            int sourceUserId, int targetUserId) {
7266        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7267        long ident = Binder.clearCallingIdentity();
7268        boolean targetIsProfile;
7269        try {
7270            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7271        } finally {
7272            Binder.restoreCallingIdentity(ident);
7273        }
7274        String className;
7275        if (targetIsProfile) {
7276            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7277        } else {
7278            className = FORWARD_INTENT_TO_PARENT;
7279        }
7280        ComponentName forwardingActivityComponentName = new ComponentName(
7281                mAndroidApplication.packageName, className);
7282        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7283                sourceUserId);
7284        if (!targetIsProfile) {
7285            forwardingActivityInfo.showUserIcon = targetUserId;
7286            forwardingResolveInfo.noResourceId = true;
7287        }
7288        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7289        forwardingResolveInfo.priority = 0;
7290        forwardingResolveInfo.preferredOrder = 0;
7291        forwardingResolveInfo.match = 0;
7292        forwardingResolveInfo.isDefault = true;
7293        forwardingResolveInfo.filter = filter;
7294        forwardingResolveInfo.targetUserId = targetUserId;
7295        return forwardingResolveInfo;
7296    }
7297
7298    @Override
7299    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7300            Intent[] specifics, String[] specificTypes, Intent intent,
7301            String resolvedType, int flags, int userId) {
7302        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7303                specificTypes, intent, resolvedType, flags, userId));
7304    }
7305
7306    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7307            Intent[] specifics, String[] specificTypes, Intent intent,
7308            String resolvedType, int flags, int userId) {
7309        if (!sUserManager.exists(userId)) return Collections.emptyList();
7310        final int callingUid = Binder.getCallingUid();
7311        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7312                false /*includeInstantApps*/);
7313        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7314                false /*requireFullPermission*/, false /*checkShell*/,
7315                "query intent activity options");
7316        final String resultsAction = intent.getAction();
7317
7318        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7319                | PackageManager.GET_RESOLVED_FILTER, userId);
7320
7321        if (DEBUG_INTENT_MATCHING) {
7322            Log.v(TAG, "Query " + intent + ": " + results);
7323        }
7324
7325        int specificsPos = 0;
7326        int N;
7327
7328        // todo: note that the algorithm used here is O(N^2).  This
7329        // isn't a problem in our current environment, but if we start running
7330        // into situations where we have more than 5 or 10 matches then this
7331        // should probably be changed to something smarter...
7332
7333        // First we go through and resolve each of the specific items
7334        // that were supplied, taking care of removing any corresponding
7335        // duplicate items in the generic resolve list.
7336        if (specifics != null) {
7337            for (int i=0; i<specifics.length; i++) {
7338                final Intent sintent = specifics[i];
7339                if (sintent == null) {
7340                    continue;
7341                }
7342
7343                if (DEBUG_INTENT_MATCHING) {
7344                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7345                }
7346
7347                String action = sintent.getAction();
7348                if (resultsAction != null && resultsAction.equals(action)) {
7349                    // If this action was explicitly requested, then don't
7350                    // remove things that have it.
7351                    action = null;
7352                }
7353
7354                ResolveInfo ri = null;
7355                ActivityInfo ai = null;
7356
7357                ComponentName comp = sintent.getComponent();
7358                if (comp == null) {
7359                    ri = resolveIntent(
7360                        sintent,
7361                        specificTypes != null ? specificTypes[i] : null,
7362                            flags, userId);
7363                    if (ri == null) {
7364                        continue;
7365                    }
7366                    if (ri == mResolveInfo) {
7367                        // ACK!  Must do something better with this.
7368                    }
7369                    ai = ri.activityInfo;
7370                    comp = new ComponentName(ai.applicationInfo.packageName,
7371                            ai.name);
7372                } else {
7373                    ai = getActivityInfo(comp, flags, userId);
7374                    if (ai == null) {
7375                        continue;
7376                    }
7377                }
7378
7379                // Look for any generic query activities that are duplicates
7380                // of this specific one, and remove them from the results.
7381                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7382                N = results.size();
7383                int j;
7384                for (j=specificsPos; j<N; j++) {
7385                    ResolveInfo sri = results.get(j);
7386                    if ((sri.activityInfo.name.equals(comp.getClassName())
7387                            && sri.activityInfo.applicationInfo.packageName.equals(
7388                                    comp.getPackageName()))
7389                        || (action != null && sri.filter.matchAction(action))) {
7390                        results.remove(j);
7391                        if (DEBUG_INTENT_MATCHING) Log.v(
7392                            TAG, "Removing duplicate item from " + j
7393                            + " due to specific " + specificsPos);
7394                        if (ri == null) {
7395                            ri = sri;
7396                        }
7397                        j--;
7398                        N--;
7399                    }
7400                }
7401
7402                // Add this specific item to its proper place.
7403                if (ri == null) {
7404                    ri = new ResolveInfo();
7405                    ri.activityInfo = ai;
7406                }
7407                results.add(specificsPos, ri);
7408                ri.specificIndex = i;
7409                specificsPos++;
7410            }
7411        }
7412
7413        // Now we go through the remaining generic results and remove any
7414        // duplicate actions that are found here.
7415        N = results.size();
7416        for (int i=specificsPos; i<N-1; i++) {
7417            final ResolveInfo rii = results.get(i);
7418            if (rii.filter == null) {
7419                continue;
7420            }
7421
7422            // Iterate over all of the actions of this result's intent
7423            // filter...  typically this should be just one.
7424            final Iterator<String> it = rii.filter.actionsIterator();
7425            if (it == null) {
7426                continue;
7427            }
7428            while (it.hasNext()) {
7429                final String action = it.next();
7430                if (resultsAction != null && resultsAction.equals(action)) {
7431                    // If this action was explicitly requested, then don't
7432                    // remove things that have it.
7433                    continue;
7434                }
7435                for (int j=i+1; j<N; j++) {
7436                    final ResolveInfo rij = results.get(j);
7437                    if (rij.filter != null && rij.filter.hasAction(action)) {
7438                        results.remove(j);
7439                        if (DEBUG_INTENT_MATCHING) Log.v(
7440                            TAG, "Removing duplicate item from " + j
7441                            + " due to action " + action + " at " + i);
7442                        j--;
7443                        N--;
7444                    }
7445                }
7446            }
7447
7448            // If the caller didn't request filter information, drop it now
7449            // so we don't have to marshall/unmarshall it.
7450            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7451                rii.filter = null;
7452            }
7453        }
7454
7455        // Filter out the caller activity if so requested.
7456        if (caller != null) {
7457            N = results.size();
7458            for (int i=0; i<N; i++) {
7459                ActivityInfo ainfo = results.get(i).activityInfo;
7460                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7461                        && caller.getClassName().equals(ainfo.name)) {
7462                    results.remove(i);
7463                    break;
7464                }
7465            }
7466        }
7467
7468        // If the caller didn't request filter information,
7469        // drop them now so we don't have to
7470        // marshall/unmarshall it.
7471        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7472            N = results.size();
7473            for (int i=0; i<N; i++) {
7474                results.get(i).filter = null;
7475            }
7476        }
7477
7478        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7479        return results;
7480    }
7481
7482    @Override
7483    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7484            String resolvedType, int flags, int userId) {
7485        return new ParceledListSlice<>(
7486                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7487                        false /*allowDynamicSplits*/));
7488    }
7489
7490    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7491            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7492        if (!sUserManager.exists(userId)) return Collections.emptyList();
7493        final int callingUid = Binder.getCallingUid();
7494        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7495                false /*requireFullPermission*/, false /*checkShell*/,
7496                "query intent receivers");
7497        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7498        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7499                false /*includeInstantApps*/);
7500        ComponentName comp = intent.getComponent();
7501        if (comp == null) {
7502            if (intent.getSelector() != null) {
7503                intent = intent.getSelector();
7504                comp = intent.getComponent();
7505            }
7506        }
7507        if (comp != null) {
7508            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7509            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7510            if (ai != null) {
7511                // When specifying an explicit component, we prevent the activity from being
7512                // used when either 1) the calling package is normal and the activity is within
7513                // an instant application or 2) the calling package is ephemeral and the
7514                // activity is not visible to instant applications.
7515                final boolean matchInstantApp =
7516                        (flags & PackageManager.MATCH_INSTANT) != 0;
7517                final boolean matchVisibleToInstantAppOnly =
7518                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7519                final boolean matchExplicitlyVisibleOnly =
7520                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7521                final boolean isCallerInstantApp =
7522                        instantAppPkgName != null;
7523                final boolean isTargetSameInstantApp =
7524                        comp.getPackageName().equals(instantAppPkgName);
7525                final boolean isTargetInstantApp =
7526                        (ai.applicationInfo.privateFlags
7527                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7528                final boolean isTargetVisibleToInstantApp =
7529                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7530                final boolean isTargetExplicitlyVisibleToInstantApp =
7531                        isTargetVisibleToInstantApp
7532                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7533                final boolean isTargetHiddenFromInstantApp =
7534                        !isTargetVisibleToInstantApp
7535                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7536                final boolean blockResolution =
7537                        !isTargetSameInstantApp
7538                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7539                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7540                                        && isTargetHiddenFromInstantApp));
7541                if (!blockResolution) {
7542                    ResolveInfo ri = new ResolveInfo();
7543                    ri.activityInfo = ai;
7544                    list.add(ri);
7545                }
7546            }
7547            return applyPostResolutionFilter(
7548                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7549        }
7550
7551        // reader
7552        synchronized (mPackages) {
7553            String pkgName = intent.getPackage();
7554            if (pkgName == null) {
7555                final List<ResolveInfo> result =
7556                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7557                return applyPostResolutionFilter(
7558                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7559            }
7560            final PackageParser.Package pkg = mPackages.get(pkgName);
7561            if (pkg != null) {
7562                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7563                        intent, resolvedType, flags, pkg.receivers, userId);
7564                return applyPostResolutionFilter(
7565                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7566            }
7567            return Collections.emptyList();
7568        }
7569    }
7570
7571    @Override
7572    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7573        final int callingUid = Binder.getCallingUid();
7574        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7575    }
7576
7577    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7578            int userId, int callingUid) {
7579        if (!sUserManager.exists(userId)) return null;
7580        flags = updateFlagsForResolve(
7581                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7582        List<ResolveInfo> query = queryIntentServicesInternal(
7583                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7584        if (query != null) {
7585            if (query.size() >= 1) {
7586                // If there is more than one service with the same priority,
7587                // just arbitrarily pick the first one.
7588                return query.get(0);
7589            }
7590        }
7591        return null;
7592    }
7593
7594    @Override
7595    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7596            String resolvedType, int flags, int userId) {
7597        final int callingUid = Binder.getCallingUid();
7598        return new ParceledListSlice<>(queryIntentServicesInternal(
7599                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7600    }
7601
7602    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7603            String resolvedType, int flags, int userId, int callingUid,
7604            boolean includeInstantApps) {
7605        if (!sUserManager.exists(userId)) return Collections.emptyList();
7606        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7607                false /*requireFullPermission*/, false /*checkShell*/,
7608                "query intent receivers");
7609        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7610        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7611        ComponentName comp = intent.getComponent();
7612        if (comp == null) {
7613            if (intent.getSelector() != null) {
7614                intent = intent.getSelector();
7615                comp = intent.getComponent();
7616            }
7617        }
7618        if (comp != null) {
7619            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7620            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7621            if (si != null) {
7622                // When specifying an explicit component, we prevent the service from being
7623                // used when either 1) the service is in an instant application and the
7624                // caller is not the same instant application or 2) the calling package is
7625                // ephemeral and the activity is not visible to ephemeral applications.
7626                final boolean matchInstantApp =
7627                        (flags & PackageManager.MATCH_INSTANT) != 0;
7628                final boolean matchVisibleToInstantAppOnly =
7629                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7630                final boolean isCallerInstantApp =
7631                        instantAppPkgName != null;
7632                final boolean isTargetSameInstantApp =
7633                        comp.getPackageName().equals(instantAppPkgName);
7634                final boolean isTargetInstantApp =
7635                        (si.applicationInfo.privateFlags
7636                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7637                final boolean isTargetHiddenFromInstantApp =
7638                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7639                final boolean blockResolution =
7640                        !isTargetSameInstantApp
7641                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7642                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7643                                        && isTargetHiddenFromInstantApp));
7644                if (!blockResolution) {
7645                    final ResolveInfo ri = new ResolveInfo();
7646                    ri.serviceInfo = si;
7647                    list.add(ri);
7648                }
7649            }
7650            return list;
7651        }
7652
7653        // reader
7654        synchronized (mPackages) {
7655            String pkgName = intent.getPackage();
7656            if (pkgName == null) {
7657                return applyPostServiceResolutionFilter(
7658                        mServices.queryIntent(intent, resolvedType, flags, userId),
7659                        instantAppPkgName);
7660            }
7661            final PackageParser.Package pkg = mPackages.get(pkgName);
7662            if (pkg != null) {
7663                return applyPostServiceResolutionFilter(
7664                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7665                                userId),
7666                        instantAppPkgName);
7667            }
7668            return Collections.emptyList();
7669        }
7670    }
7671
7672    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7673            String instantAppPkgName) {
7674        if (instantAppPkgName == null) {
7675            return resolveInfos;
7676        }
7677        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7678            final ResolveInfo info = resolveInfos.get(i);
7679            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7680            // allow services that are defined in the provided package
7681            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7682                if (info.serviceInfo.splitName != null
7683                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7684                                info.serviceInfo.splitName)) {
7685                    // requested service is defined in a split that hasn't been installed yet.
7686                    // add the installer to the resolve list
7687                    if (DEBUG_INSTANT) {
7688                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7689                    }
7690                    final ResolveInfo installerInfo = new ResolveInfo(
7691                            mInstantAppInstallerInfo);
7692                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7693                            null /* installFailureActivity */,
7694                            info.serviceInfo.packageName,
7695                            info.serviceInfo.applicationInfo.versionCode,
7696                            info.serviceInfo.splitName);
7697                    // add a non-generic filter
7698                    installerInfo.filter = new IntentFilter();
7699                    // load resources from the correct package
7700                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7701                    resolveInfos.set(i, installerInfo);
7702                }
7703                continue;
7704            }
7705            // allow services that have been explicitly exposed to ephemeral apps
7706            if (!isEphemeralApp
7707                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7708                continue;
7709            }
7710            resolveInfos.remove(i);
7711        }
7712        return resolveInfos;
7713    }
7714
7715    @Override
7716    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7717            String resolvedType, int flags, int userId) {
7718        return new ParceledListSlice<>(
7719                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7720    }
7721
7722    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7723            Intent intent, String resolvedType, int flags, int userId) {
7724        if (!sUserManager.exists(userId)) return Collections.emptyList();
7725        final int callingUid = Binder.getCallingUid();
7726        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7727        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7728                false /*includeInstantApps*/);
7729        ComponentName comp = intent.getComponent();
7730        if (comp == null) {
7731            if (intent.getSelector() != null) {
7732                intent = intent.getSelector();
7733                comp = intent.getComponent();
7734            }
7735        }
7736        if (comp != null) {
7737            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7738            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7739            if (pi != null) {
7740                // When specifying an explicit component, we prevent the provider from being
7741                // used when either 1) the provider is in an instant application and the
7742                // caller is not the same instant application or 2) the calling package is an
7743                // instant application and the provider is not visible to instant applications.
7744                final boolean matchInstantApp =
7745                        (flags & PackageManager.MATCH_INSTANT) != 0;
7746                final boolean matchVisibleToInstantAppOnly =
7747                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7748                final boolean isCallerInstantApp =
7749                        instantAppPkgName != null;
7750                final boolean isTargetSameInstantApp =
7751                        comp.getPackageName().equals(instantAppPkgName);
7752                final boolean isTargetInstantApp =
7753                        (pi.applicationInfo.privateFlags
7754                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7755                final boolean isTargetHiddenFromInstantApp =
7756                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7757                final boolean blockResolution =
7758                        !isTargetSameInstantApp
7759                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7760                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7761                                        && isTargetHiddenFromInstantApp));
7762                if (!blockResolution) {
7763                    final ResolveInfo ri = new ResolveInfo();
7764                    ri.providerInfo = pi;
7765                    list.add(ri);
7766                }
7767            }
7768            return list;
7769        }
7770
7771        // reader
7772        synchronized (mPackages) {
7773            String pkgName = intent.getPackage();
7774            if (pkgName == null) {
7775                return applyPostContentProviderResolutionFilter(
7776                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7777                        instantAppPkgName);
7778            }
7779            final PackageParser.Package pkg = mPackages.get(pkgName);
7780            if (pkg != null) {
7781                return applyPostContentProviderResolutionFilter(
7782                        mProviders.queryIntentForPackage(
7783                        intent, resolvedType, flags, pkg.providers, userId),
7784                        instantAppPkgName);
7785            }
7786            return Collections.emptyList();
7787        }
7788    }
7789
7790    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7791            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7792        if (instantAppPkgName == null) {
7793            return resolveInfos;
7794        }
7795        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7796            final ResolveInfo info = resolveInfos.get(i);
7797            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7798            // allow providers that are defined in the provided package
7799            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7800                if (info.providerInfo.splitName != null
7801                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7802                                info.providerInfo.splitName)) {
7803                    // requested provider is defined in a split that hasn't been installed yet.
7804                    // add the installer to the resolve list
7805                    if (DEBUG_INSTANT) {
7806                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7807                    }
7808                    final ResolveInfo installerInfo = new ResolveInfo(
7809                            mInstantAppInstallerInfo);
7810                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7811                            null /*failureActivity*/,
7812                            info.providerInfo.packageName,
7813                            info.providerInfo.applicationInfo.versionCode,
7814                            info.providerInfo.splitName);
7815                    // add a non-generic filter
7816                    installerInfo.filter = new IntentFilter();
7817                    // load resources from the correct package
7818                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7819                    resolveInfos.set(i, installerInfo);
7820                }
7821                continue;
7822            }
7823            // allow providers that have been explicitly exposed to instant applications
7824            if (!isEphemeralApp
7825                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7826                continue;
7827            }
7828            resolveInfos.remove(i);
7829        }
7830        return resolveInfos;
7831    }
7832
7833    @Override
7834    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7835        final int callingUid = Binder.getCallingUid();
7836        if (getInstantAppPackageName(callingUid) != null) {
7837            return ParceledListSlice.emptyList();
7838        }
7839        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7840        flags = updateFlagsForPackage(flags, userId, null);
7841        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7842        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7843                true /* requireFullPermission */, false /* checkShell */,
7844                "get installed packages");
7845
7846        // writer
7847        synchronized (mPackages) {
7848            ArrayList<PackageInfo> list;
7849            if (listUninstalled) {
7850                list = new ArrayList<>(mSettings.mPackages.size());
7851                for (PackageSetting ps : mSettings.mPackages.values()) {
7852                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7853                        continue;
7854                    }
7855                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7856                        continue;
7857                    }
7858                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7859                    if (pi != null) {
7860                        list.add(pi);
7861                    }
7862                }
7863            } else {
7864                list = new ArrayList<>(mPackages.size());
7865                for (PackageParser.Package p : mPackages.values()) {
7866                    final PackageSetting ps = (PackageSetting) p.mExtras;
7867                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7868                        continue;
7869                    }
7870                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7871                        continue;
7872                    }
7873                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7874                            p.mExtras, flags, userId);
7875                    if (pi != null) {
7876                        list.add(pi);
7877                    }
7878                }
7879            }
7880
7881            return new ParceledListSlice<>(list);
7882        }
7883    }
7884
7885    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7886            String[] permissions, boolean[] tmp, int flags, int userId) {
7887        int numMatch = 0;
7888        final PermissionsState permissionsState = ps.getPermissionsState();
7889        for (int i=0; i<permissions.length; i++) {
7890            final String permission = permissions[i];
7891            if (permissionsState.hasPermission(permission, userId)) {
7892                tmp[i] = true;
7893                numMatch++;
7894            } else {
7895                tmp[i] = false;
7896            }
7897        }
7898        if (numMatch == 0) {
7899            return;
7900        }
7901        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7902
7903        // The above might return null in cases of uninstalled apps or install-state
7904        // skew across users/profiles.
7905        if (pi != null) {
7906            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7907                if (numMatch == permissions.length) {
7908                    pi.requestedPermissions = permissions;
7909                } else {
7910                    pi.requestedPermissions = new String[numMatch];
7911                    numMatch = 0;
7912                    for (int i=0; i<permissions.length; i++) {
7913                        if (tmp[i]) {
7914                            pi.requestedPermissions[numMatch] = permissions[i];
7915                            numMatch++;
7916                        }
7917                    }
7918                }
7919            }
7920            list.add(pi);
7921        }
7922    }
7923
7924    @Override
7925    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7926            String[] permissions, int flags, int userId) {
7927        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7928        flags = updateFlagsForPackage(flags, userId, permissions);
7929        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7930                true /* requireFullPermission */, false /* checkShell */,
7931                "get packages holding permissions");
7932        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7933
7934        // writer
7935        synchronized (mPackages) {
7936            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7937            boolean[] tmpBools = new boolean[permissions.length];
7938            if (listUninstalled) {
7939                for (PackageSetting ps : mSettings.mPackages.values()) {
7940                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7941                            userId);
7942                }
7943            } else {
7944                for (PackageParser.Package pkg : mPackages.values()) {
7945                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7946                    if (ps != null) {
7947                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7948                                userId);
7949                    }
7950                }
7951            }
7952
7953            return new ParceledListSlice<PackageInfo>(list);
7954        }
7955    }
7956
7957    @Override
7958    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7959        final int callingUid = Binder.getCallingUid();
7960        if (getInstantAppPackageName(callingUid) != null) {
7961            return ParceledListSlice.emptyList();
7962        }
7963        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7964        flags = updateFlagsForApplication(flags, userId, null);
7965        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7966
7967        // writer
7968        synchronized (mPackages) {
7969            ArrayList<ApplicationInfo> list;
7970            if (listUninstalled) {
7971                list = new ArrayList<>(mSettings.mPackages.size());
7972                for (PackageSetting ps : mSettings.mPackages.values()) {
7973                    ApplicationInfo ai;
7974                    int effectiveFlags = flags;
7975                    if (ps.isSystem()) {
7976                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7977                    }
7978                    if (ps.pkg != null) {
7979                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7980                            continue;
7981                        }
7982                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7983                            continue;
7984                        }
7985                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7986                                ps.readUserState(userId), userId);
7987                        if (ai != null) {
7988                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7989                        }
7990                    } else {
7991                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7992                        // and already converts to externally visible package name
7993                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7994                                callingUid, effectiveFlags, userId);
7995                    }
7996                    if (ai != null) {
7997                        list.add(ai);
7998                    }
7999                }
8000            } else {
8001                list = new ArrayList<>(mPackages.size());
8002                for (PackageParser.Package p : mPackages.values()) {
8003                    if (p.mExtras != null) {
8004                        PackageSetting ps = (PackageSetting) p.mExtras;
8005                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8006                            continue;
8007                        }
8008                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8009                            continue;
8010                        }
8011                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8012                                ps.readUserState(userId), userId);
8013                        if (ai != null) {
8014                            ai.packageName = resolveExternalPackageNameLPr(p);
8015                            list.add(ai);
8016                        }
8017                    }
8018                }
8019            }
8020
8021            return new ParceledListSlice<>(list);
8022        }
8023    }
8024
8025    @Override
8026    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8027        if (HIDE_EPHEMERAL_APIS) {
8028            return null;
8029        }
8030        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8031            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8032                    "getEphemeralApplications");
8033        }
8034        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8035                true /* requireFullPermission */, false /* checkShell */,
8036                "getEphemeralApplications");
8037        synchronized (mPackages) {
8038            List<InstantAppInfo> instantApps = mInstantAppRegistry
8039                    .getInstantAppsLPr(userId);
8040            if (instantApps != null) {
8041                return new ParceledListSlice<>(instantApps);
8042            }
8043        }
8044        return null;
8045    }
8046
8047    @Override
8048    public boolean isInstantApp(String packageName, int userId) {
8049        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8050                true /* requireFullPermission */, false /* checkShell */,
8051                "isInstantApp");
8052        if (HIDE_EPHEMERAL_APIS) {
8053            return false;
8054        }
8055
8056        synchronized (mPackages) {
8057            int callingUid = Binder.getCallingUid();
8058            if (Process.isIsolated(callingUid)) {
8059                callingUid = mIsolatedOwners.get(callingUid);
8060            }
8061            final PackageSetting ps = mSettings.mPackages.get(packageName);
8062            PackageParser.Package pkg = mPackages.get(packageName);
8063            final boolean returnAllowed =
8064                    ps != null
8065                    && (isCallerSameApp(packageName, callingUid)
8066                            || canViewInstantApps(callingUid, userId)
8067                            || mInstantAppRegistry.isInstantAccessGranted(
8068                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8069            if (returnAllowed) {
8070                return ps.getInstantApp(userId);
8071            }
8072        }
8073        return false;
8074    }
8075
8076    @Override
8077    public byte[] getInstantAppCookie(String packageName, int userId) {
8078        if (HIDE_EPHEMERAL_APIS) {
8079            return null;
8080        }
8081
8082        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8083                true /* requireFullPermission */, false /* checkShell */,
8084                "getInstantAppCookie");
8085        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8086            return null;
8087        }
8088        synchronized (mPackages) {
8089            return mInstantAppRegistry.getInstantAppCookieLPw(
8090                    packageName, userId);
8091        }
8092    }
8093
8094    @Override
8095    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8096        if (HIDE_EPHEMERAL_APIS) {
8097            return true;
8098        }
8099
8100        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8101                true /* requireFullPermission */, true /* checkShell */,
8102                "setInstantAppCookie");
8103        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8104            return false;
8105        }
8106        synchronized (mPackages) {
8107            return mInstantAppRegistry.setInstantAppCookieLPw(
8108                    packageName, cookie, userId);
8109        }
8110    }
8111
8112    @Override
8113    public Bitmap getInstantAppIcon(String packageName, int userId) {
8114        if (HIDE_EPHEMERAL_APIS) {
8115            return null;
8116        }
8117
8118        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8119            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8120                    "getInstantAppIcon");
8121        }
8122        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8123                true /* requireFullPermission */, false /* checkShell */,
8124                "getInstantAppIcon");
8125
8126        synchronized (mPackages) {
8127            return mInstantAppRegistry.getInstantAppIconLPw(
8128                    packageName, userId);
8129        }
8130    }
8131
8132    private boolean isCallerSameApp(String packageName, int uid) {
8133        PackageParser.Package pkg = mPackages.get(packageName);
8134        return pkg != null
8135                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8136    }
8137
8138    @Override
8139    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8140        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8141            return ParceledListSlice.emptyList();
8142        }
8143        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8144    }
8145
8146    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8147        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8148
8149        // reader
8150        synchronized (mPackages) {
8151            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8152            final int userId = UserHandle.getCallingUserId();
8153            while (i.hasNext()) {
8154                final PackageParser.Package p = i.next();
8155                if (p.applicationInfo == null) continue;
8156
8157                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8158                        && !p.applicationInfo.isDirectBootAware();
8159                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8160                        && p.applicationInfo.isDirectBootAware();
8161
8162                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8163                        && (!mSafeMode || isSystemApp(p))
8164                        && (matchesUnaware || matchesAware)) {
8165                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8166                    if (ps != null) {
8167                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8168                                ps.readUserState(userId), userId);
8169                        if (ai != null) {
8170                            finalList.add(ai);
8171                        }
8172                    }
8173                }
8174            }
8175        }
8176
8177        return finalList;
8178    }
8179
8180    @Override
8181    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8182        return resolveContentProviderInternal(name, flags, userId);
8183    }
8184
8185    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8186        if (!sUserManager.exists(userId)) return null;
8187        flags = updateFlagsForComponent(flags, userId, name);
8188        final int callingUid = Binder.getCallingUid();
8189        synchronized (mPackages) {
8190            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8191            PackageSetting ps = provider != null
8192                    ? mSettings.mPackages.get(provider.owner.packageName)
8193                    : null;
8194            if (ps != null) {
8195                // provider not enabled
8196                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8197                    return null;
8198                }
8199                final ComponentName component =
8200                        new ComponentName(provider.info.packageName, provider.info.name);
8201                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8202                    return null;
8203                }
8204                return PackageParser.generateProviderInfo(
8205                        provider, flags, ps.readUserState(userId), userId);
8206            }
8207            return null;
8208        }
8209    }
8210
8211    /**
8212     * @deprecated
8213     */
8214    @Deprecated
8215    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8216        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8217            return;
8218        }
8219        // reader
8220        synchronized (mPackages) {
8221            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8222                    .entrySet().iterator();
8223            final int userId = UserHandle.getCallingUserId();
8224            while (i.hasNext()) {
8225                Map.Entry<String, PackageParser.Provider> entry = i.next();
8226                PackageParser.Provider p = entry.getValue();
8227                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8228
8229                if (ps != null && p.syncable
8230                        && (!mSafeMode || (p.info.applicationInfo.flags
8231                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8232                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8233                            ps.readUserState(userId), userId);
8234                    if (info != null) {
8235                        outNames.add(entry.getKey());
8236                        outInfo.add(info);
8237                    }
8238                }
8239            }
8240        }
8241    }
8242
8243    @Override
8244    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8245            int uid, int flags, String metaDataKey) {
8246        final int callingUid = Binder.getCallingUid();
8247        final int userId = processName != null ? UserHandle.getUserId(uid)
8248                : UserHandle.getCallingUserId();
8249        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8250        flags = updateFlagsForComponent(flags, userId, processName);
8251        ArrayList<ProviderInfo> finalList = null;
8252        // reader
8253        synchronized (mPackages) {
8254            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8255            while (i.hasNext()) {
8256                final PackageParser.Provider p = i.next();
8257                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8258                if (ps != null && p.info.authority != null
8259                        && (processName == null
8260                                || (p.info.processName.equals(processName)
8261                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8262                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8263
8264                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8265                    // parameter.
8266                    if (metaDataKey != null
8267                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8268                        continue;
8269                    }
8270                    final ComponentName component =
8271                            new ComponentName(p.info.packageName, p.info.name);
8272                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8273                        continue;
8274                    }
8275                    if (finalList == null) {
8276                        finalList = new ArrayList<ProviderInfo>(3);
8277                    }
8278                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8279                            ps.readUserState(userId), userId);
8280                    if (info != null) {
8281                        finalList.add(info);
8282                    }
8283                }
8284            }
8285        }
8286
8287        if (finalList != null) {
8288            Collections.sort(finalList, mProviderInitOrderSorter);
8289            return new ParceledListSlice<ProviderInfo>(finalList);
8290        }
8291
8292        return ParceledListSlice.emptyList();
8293    }
8294
8295    @Override
8296    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8297        // reader
8298        synchronized (mPackages) {
8299            final int callingUid = Binder.getCallingUid();
8300            final int callingUserId = UserHandle.getUserId(callingUid);
8301            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8302            if (ps == null) return null;
8303            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8304                return null;
8305            }
8306            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8307            return PackageParser.generateInstrumentationInfo(i, flags);
8308        }
8309    }
8310
8311    @Override
8312    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8313            String targetPackage, int flags) {
8314        final int callingUid = Binder.getCallingUid();
8315        final int callingUserId = UserHandle.getUserId(callingUid);
8316        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8317        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8318            return ParceledListSlice.emptyList();
8319        }
8320        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8321    }
8322
8323    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8324            int flags) {
8325        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8326
8327        // reader
8328        synchronized (mPackages) {
8329            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8330            while (i.hasNext()) {
8331                final PackageParser.Instrumentation p = i.next();
8332                if (targetPackage == null
8333                        || targetPackage.equals(p.info.targetPackage)) {
8334                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8335                            flags);
8336                    if (ii != null) {
8337                        finalList.add(ii);
8338                    }
8339                }
8340            }
8341        }
8342
8343        return finalList;
8344    }
8345
8346    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8347        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8348        try {
8349            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8350        } finally {
8351            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8352        }
8353    }
8354
8355    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8356        final File[] files = scanDir.listFiles();
8357        if (ArrayUtils.isEmpty(files)) {
8358            Log.d(TAG, "No files in app dir " + scanDir);
8359            return;
8360        }
8361
8362        if (DEBUG_PACKAGE_SCANNING) {
8363            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8364                    + " flags=0x" + Integer.toHexString(parseFlags));
8365        }
8366        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8367                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8368                mParallelPackageParserCallback)) {
8369            // Submit files for parsing in parallel
8370            int fileCount = 0;
8371            for (File file : files) {
8372                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8373                        && !PackageInstallerService.isStageName(file.getName());
8374                if (!isPackage) {
8375                    // Ignore entries which are not packages
8376                    continue;
8377                }
8378                parallelPackageParser.submit(file, parseFlags);
8379                fileCount++;
8380            }
8381
8382            // Process results one by one
8383            for (; fileCount > 0; fileCount--) {
8384                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8385                Throwable throwable = parseResult.throwable;
8386                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8387
8388                if (throwable == null) {
8389                    // TODO(toddke): move lower in the scan chain
8390                    // Static shared libraries have synthetic package names
8391                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8392                        renameStaticSharedLibraryPackage(parseResult.pkg);
8393                    }
8394                    try {
8395                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8396                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8397                                    currentTime, null);
8398                        }
8399                    } catch (PackageManagerException e) {
8400                        errorCode = e.error;
8401                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8402                    }
8403                } else if (throwable instanceof PackageParser.PackageParserException) {
8404                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8405                            throwable;
8406                    errorCode = e.error;
8407                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8408                } else {
8409                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8410                            + parseResult.scanFile, throwable);
8411                }
8412
8413                // Delete invalid userdata apps
8414                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8415                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8416                    logCriticalInfo(Log.WARN,
8417                            "Deleting invalid package at " + parseResult.scanFile);
8418                    removeCodePathLI(parseResult.scanFile);
8419                }
8420            }
8421        }
8422    }
8423
8424    public static void reportSettingsProblem(int priority, String msg) {
8425        logCriticalInfo(priority, msg);
8426    }
8427
8428    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8429            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8430        // When upgrading from pre-N MR1, verify the package time stamp using the package
8431        // directory and not the APK file.
8432        final long lastModifiedTime = mIsPreNMR1Upgrade
8433                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8434        if (ps != null && !forceCollect
8435                && ps.codePathString.equals(pkg.codePath)
8436                && ps.timeStamp == lastModifiedTime
8437                && !isCompatSignatureUpdateNeeded(pkg)
8438                && !isRecoverSignatureUpdateNeeded(pkg)) {
8439            if (ps.signatures.mSigningDetails.signatures != null
8440                    && ps.signatures.mSigningDetails.signatures.length != 0
8441                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8442                            != SignatureSchemeVersion.UNKNOWN) {
8443                // Optimization: reuse the existing cached signing data
8444                // if the package appears to be unchanged.
8445                pkg.mSigningDetails =
8446                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8447                return;
8448            }
8449
8450            Slog.w(TAG, "PackageSetting for " + ps.name
8451                    + " is missing signatures.  Collecting certs again to recover them.");
8452        } else {
8453            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8454                    (forceCollect ? " (forced)" : ""));
8455        }
8456
8457        try {
8458            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8459            PackageParser.collectCertificates(pkg, skipVerify);
8460        } catch (PackageParserException e) {
8461            throw PackageManagerException.from(e);
8462        } finally {
8463            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8464        }
8465    }
8466
8467    /**
8468     *  Traces a package scan.
8469     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8470     */
8471    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8472            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8473        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8474        try {
8475            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8476        } finally {
8477            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8478        }
8479    }
8480
8481    /**
8482     *  Scans a package and returns the newly parsed package.
8483     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8484     */
8485    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8486            long currentTime, UserHandle user) throws PackageManagerException {
8487        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8488        PackageParser pp = new PackageParser();
8489        pp.setSeparateProcesses(mSeparateProcesses);
8490        pp.setOnlyCoreApps(mOnlyCore);
8491        pp.setDisplayMetrics(mMetrics);
8492        pp.setCallback(mPackageParserCallback);
8493
8494        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8495        final PackageParser.Package pkg;
8496        try {
8497            pkg = pp.parsePackage(scanFile, parseFlags);
8498        } catch (PackageParserException e) {
8499            throw PackageManagerException.from(e);
8500        } finally {
8501            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8502        }
8503
8504        // Static shared libraries have synthetic package names
8505        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8506            renameStaticSharedLibraryPackage(pkg);
8507        }
8508
8509        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8510    }
8511
8512    /**
8513     *  Scans a package and returns the newly parsed package.
8514     *  @throws PackageManagerException on a parse error.
8515     */
8516    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8517            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8518            @Nullable UserHandle user)
8519                    throws PackageManagerException {
8520        // If the package has children and this is the first dive in the function
8521        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8522        // packages (parent and children) would be successfully scanned before the
8523        // actual scan since scanning mutates internal state and we want to atomically
8524        // install the package and its children.
8525        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8526            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8527                scanFlags |= SCAN_CHECK_ONLY;
8528            }
8529        } else {
8530            scanFlags &= ~SCAN_CHECK_ONLY;
8531        }
8532
8533        // Scan the parent
8534        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8535                scanFlags, currentTime, user);
8536
8537        // Scan the children
8538        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8539        for (int i = 0; i < childCount; i++) {
8540            PackageParser.Package childPackage = pkg.childPackages.get(i);
8541            addForInitLI(childPackage, parseFlags, scanFlags,
8542                    currentTime, user);
8543        }
8544
8545
8546        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8547            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8548        }
8549
8550        return scannedPkg;
8551    }
8552
8553    /**
8554     * Returns if full apk verification can be skipped for the whole package, including the splits.
8555     */
8556    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8557        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8558            return false;
8559        }
8560        // TODO: Allow base and splits to be verified individually.
8561        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8562            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8563                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8564                    return false;
8565                }
8566            }
8567        }
8568        return true;
8569    }
8570
8571    /**
8572     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8573     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8574     * match one in a trusted source, and should be done separately.
8575     */
8576    private boolean canSkipFullApkVerification(String apkPath) {
8577        byte[] rootHashObserved = null;
8578        try {
8579            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8580            if (rootHashObserved == null) {
8581                return false;  // APK does not contain Merkle tree root hash.
8582            }
8583            synchronized (mInstallLock) {
8584                // Returns whether the observed root hash matches what kernel has.
8585                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8586                return true;
8587            }
8588        } catch (InstallerException | IOException | DigestException |
8589                NoSuchAlgorithmException e) {
8590            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8591        }
8592        return false;
8593    }
8594
8595    /**
8596     * Adds a new package to the internal data structures during platform initialization.
8597     * <p>After adding, the package is known to the system and available for querying.
8598     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8599     * etc...], additional checks are performed. Basic verification [such as ensuring
8600     * matching signatures, checking version codes, etc...] occurs if the package is
8601     * identical to a previously known package. If the package fails a signature check,
8602     * the version installed on /data will be removed. If the version of the new package
8603     * is less than or equal than the version on /data, it will be ignored.
8604     * <p>Regardless of the package location, the results are applied to the internal
8605     * structures and the package is made available to the rest of the system.
8606     * <p>NOTE: The return value should be removed. It's the passed in package object.
8607     */
8608    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8609            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8610            @Nullable UserHandle user)
8611                    throws PackageManagerException {
8612        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8613        final String renamedPkgName;
8614        final PackageSetting disabledPkgSetting;
8615        final boolean isSystemPkgUpdated;
8616        final boolean pkgAlreadyExists;
8617        PackageSetting pkgSetting;
8618
8619        // NOTE: installPackageLI() has the same code to setup the package's
8620        // application info. This probably should be done lower in the call
8621        // stack [such as scanPackageOnly()]. However, we verify the application
8622        // info prior to that [in scanPackageNew()] and thus have to setup
8623        // the application info early.
8624        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8625        pkg.setApplicationInfoCodePath(pkg.codePath);
8626        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8627        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8628        pkg.setApplicationInfoResourcePath(pkg.codePath);
8629        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8630        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8631
8632        synchronized (mPackages) {
8633            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8634            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8635            if (realPkgName != null) {
8636                ensurePackageRenamed(pkg, renamedPkgName);
8637            }
8638            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8639            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8640            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8641            pkgAlreadyExists = pkgSetting != null;
8642            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8643            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8644            isSystemPkgUpdated = disabledPkgSetting != null;
8645
8646            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8647                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8648            }
8649
8650            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8651                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8652                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8653                    : null;
8654            if (DEBUG_PACKAGE_SCANNING
8655                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8656                    && sharedUserSetting != null) {
8657                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8658                        + " (uid=" + sharedUserSetting.userId + "):"
8659                        + " packages=" + sharedUserSetting.packages);
8660            }
8661
8662            if (scanSystemPartition) {
8663                // Potentially prune child packages. If the application on the /system
8664                // partition has been updated via OTA, but, is still disabled by a
8665                // version on /data, cycle through all of its children packages and
8666                // remove children that are no longer defined.
8667                if (isSystemPkgUpdated) {
8668                    final int scannedChildCount = (pkg.childPackages != null)
8669                            ? pkg.childPackages.size() : 0;
8670                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8671                            ? disabledPkgSetting.childPackageNames.size() : 0;
8672                    for (int i = 0; i < disabledChildCount; i++) {
8673                        String disabledChildPackageName =
8674                                disabledPkgSetting.childPackageNames.get(i);
8675                        boolean disabledPackageAvailable = false;
8676                        for (int j = 0; j < scannedChildCount; j++) {
8677                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8678                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8679                                disabledPackageAvailable = true;
8680                                break;
8681                            }
8682                        }
8683                        if (!disabledPackageAvailable) {
8684                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8685                        }
8686                    }
8687                    // we're updating the disabled package, so, scan it as the package setting
8688                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8689                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8690                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8691                            (pkg == mPlatformPackage), user);
8692                    applyPolicy(pkg, parseFlags, scanFlags);
8693                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8694                }
8695            }
8696        }
8697
8698        final boolean newPkgChangedPaths =
8699                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8700        final boolean newPkgVersionGreater =
8701                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8702        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8703                && newPkgChangedPaths && newPkgVersionGreater;
8704        if (isSystemPkgBetter) {
8705            // The version of the application on /system is greater than the version on
8706            // /data. Switch back to the application on /system.
8707            // It's safe to assume the application on /system will correctly scan. If not,
8708            // there won't be a working copy of the application.
8709            synchronized (mPackages) {
8710                // just remove the loaded entries from package lists
8711                mPackages.remove(pkgSetting.name);
8712            }
8713
8714            logCriticalInfo(Log.WARN,
8715                    "System package updated;"
8716                    + " name: " + pkgSetting.name
8717                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8718                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8719
8720            final InstallArgs args = createInstallArgsForExisting(
8721                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8722                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8723            args.cleanUpResourcesLI();
8724            synchronized (mPackages) {
8725                mSettings.enableSystemPackageLPw(pkgSetting.name);
8726            }
8727        }
8728
8729        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8730            // The version of the application on the /system partition is less than or
8731            // equal to the version on the /data partition. Throw an exception and use
8732            // the application already installed on the /data partition.
8733            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8734                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8735                    + " better than this " + pkg.getLongVersionCode());
8736        }
8737
8738        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8739        // force re-collecting certificate.
8740        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8741                disabledPkgSetting);
8742        // Full APK verification can be skipped during certificate collection, only if the file is
8743        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8744        // cases, only data in Signing Block is verified instead of the whole file.
8745        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8746                (forceCollect && canSkipFullPackageVerification(pkg));
8747        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8748
8749        boolean shouldHideSystemApp = false;
8750        // A new application appeared on /system, but, we already have a copy of
8751        // the application installed on /data.
8752        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8753                && !pkgSetting.isSystem()) {
8754
8755            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8756                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
8757                            && !pkgSetting.signatures.mSigningDetails.checkCapability(
8758                                    pkg.mSigningDetails,
8759                                    PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
8760                logCriticalInfo(Log.WARN,
8761                        "System package signature mismatch;"
8762                        + " name: " + pkgSetting.name);
8763                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8764                        "scanPackageInternalLI")) {
8765                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8766                }
8767                pkgSetting = null;
8768            } else if (newPkgVersionGreater) {
8769                // The application on /system is newer than the application on /data.
8770                // Simply remove the application on /data [keeping application data]
8771                // and replace it with the version on /system.
8772                logCriticalInfo(Log.WARN,
8773                        "System package enabled;"
8774                        + " name: " + pkgSetting.name
8775                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8776                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8777                InstallArgs args = createInstallArgsForExisting(
8778                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8779                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8780                synchronized (mInstallLock) {
8781                    args.cleanUpResourcesLI();
8782                }
8783            } else {
8784                // The application on /system is older than the application on /data. Hide
8785                // the application on /system and the version on /data will be scanned later
8786                // and re-added like an update.
8787                shouldHideSystemApp = true;
8788                logCriticalInfo(Log.INFO,
8789                        "System package disabled;"
8790                        + " name: " + pkgSetting.name
8791                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8792                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8793            }
8794        }
8795
8796        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8797                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8798
8799        if (shouldHideSystemApp) {
8800            synchronized (mPackages) {
8801                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8802            }
8803        }
8804        return scannedPkg;
8805    }
8806
8807    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8808        // Derive the new package synthetic package name
8809        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8810                + pkg.staticSharedLibVersion);
8811    }
8812
8813    private static String fixProcessName(String defProcessName,
8814            String processName) {
8815        if (processName == null) {
8816            return defProcessName;
8817        }
8818        return processName;
8819    }
8820
8821    /**
8822     * Enforces that only the system UID or root's UID can call a method exposed
8823     * via Binder.
8824     *
8825     * @param message used as message if SecurityException is thrown
8826     * @throws SecurityException if the caller is not system or root
8827     */
8828    private static final void enforceSystemOrRoot(String message) {
8829        final int uid = Binder.getCallingUid();
8830        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8831            throw new SecurityException(message);
8832        }
8833    }
8834
8835    @Override
8836    public void performFstrimIfNeeded() {
8837        enforceSystemOrRoot("Only the system can request fstrim");
8838
8839        // Before everything else, see whether we need to fstrim.
8840        try {
8841            IStorageManager sm = PackageHelper.getStorageManager();
8842            if (sm != null) {
8843                boolean doTrim = false;
8844                final long interval = android.provider.Settings.Global.getLong(
8845                        mContext.getContentResolver(),
8846                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8847                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8848                if (interval > 0) {
8849                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8850                    if (timeSinceLast > interval) {
8851                        doTrim = true;
8852                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8853                                + "; running immediately");
8854                    }
8855                }
8856                if (doTrim) {
8857                    final boolean dexOptDialogShown;
8858                    synchronized (mPackages) {
8859                        dexOptDialogShown = mDexOptDialogShown;
8860                    }
8861                    if (!isFirstBoot() && dexOptDialogShown) {
8862                        try {
8863                            ActivityManager.getService().showBootMessage(
8864                                    mContext.getResources().getString(
8865                                            R.string.android_upgrading_fstrim), true);
8866                        } catch (RemoteException e) {
8867                        }
8868                    }
8869                    sm.runMaintenance();
8870                }
8871            } else {
8872                Slog.e(TAG, "storageManager service unavailable!");
8873            }
8874        } catch (RemoteException e) {
8875            // Can't happen; StorageManagerService is local
8876        }
8877    }
8878
8879    @Override
8880    public void updatePackagesIfNeeded() {
8881        enforceSystemOrRoot("Only the system can request package update");
8882
8883        // We need to re-extract after an OTA.
8884        boolean causeUpgrade = isUpgrade();
8885
8886        // First boot or factory reset.
8887        // Note: we also handle devices that are upgrading to N right now as if it is their
8888        //       first boot, as they do not have profile data.
8889        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8890
8891        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8892        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8893
8894        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8895            return;
8896        }
8897
8898        List<PackageParser.Package> pkgs;
8899        synchronized (mPackages) {
8900            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8901        }
8902
8903        final long startTime = System.nanoTime();
8904        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8905                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8906                    false /* bootComplete */);
8907
8908        final int elapsedTimeSeconds =
8909                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8910
8911        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8912        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8913        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8914        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8915        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8916    }
8917
8918    /*
8919     * Return the prebuilt profile path given a package base code path.
8920     */
8921    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8922        return pkg.baseCodePath + ".prof";
8923    }
8924
8925    /**
8926     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8927     * containing statistics about the invocation. The array consists of three elements,
8928     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8929     * and {@code numberOfPackagesFailed}.
8930     */
8931    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8932            final int compilationReason, boolean bootComplete) {
8933
8934        int numberOfPackagesVisited = 0;
8935        int numberOfPackagesOptimized = 0;
8936        int numberOfPackagesSkipped = 0;
8937        int numberOfPackagesFailed = 0;
8938        final int numberOfPackagesToDexopt = pkgs.size();
8939
8940        for (PackageParser.Package pkg : pkgs) {
8941            numberOfPackagesVisited++;
8942
8943            boolean useProfileForDexopt = false;
8944
8945            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8946                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8947                // that are already compiled.
8948                File profileFile = new File(getPrebuildProfilePath(pkg));
8949                // Copy profile if it exists.
8950                if (profileFile.exists()) {
8951                    try {
8952                        // We could also do this lazily before calling dexopt in
8953                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8954                        // is that we don't have a good way to say "do this only once".
8955                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8956                                pkg.applicationInfo.uid, pkg.packageName,
8957                                ArtManager.getProfileName(null))) {
8958                            Log.e(TAG, "Installer failed to copy system profile!");
8959                        } else {
8960                            // Disabled as this causes speed-profile compilation during first boot
8961                            // even if things are already compiled.
8962                            // useProfileForDexopt = true;
8963                        }
8964                    } catch (Exception e) {
8965                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8966                                e);
8967                    }
8968                } else {
8969                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8970                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8971                    // minimize the number off apps being speed-profile compiled during first boot.
8972                    // The other paths will not change the filter.
8973                    if (disabledPs != null && disabledPs.pkg.isStub) {
8974                        // The package is the stub one, remove the stub suffix to get the normal
8975                        // package and APK names.
8976                        String systemProfilePath =
8977                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8978                        profileFile = new File(systemProfilePath);
8979                        // If we have a profile for a compressed APK, copy it to the reference
8980                        // location.
8981                        // Note that copying the profile here will cause it to override the
8982                        // reference profile every OTA even though the existing reference profile
8983                        // may have more data. We can't copy during decompression since the
8984                        // directories are not set up at that point.
8985                        if (profileFile.exists()) {
8986                            try {
8987                                // We could also do this lazily before calling dexopt in
8988                                // PackageDexOptimizer to prevent this happening on first boot. The
8989                                // issue is that we don't have a good way to say "do this only
8990                                // once".
8991                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8992                                        pkg.applicationInfo.uid, pkg.packageName,
8993                                        ArtManager.getProfileName(null))) {
8994                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8995                                } else {
8996                                    useProfileForDexopt = true;
8997                                }
8998                            } catch (Exception e) {
8999                                Log.e(TAG, "Failed to copy profile " +
9000                                        profileFile.getAbsolutePath() + " ", e);
9001                            }
9002                        }
9003                    }
9004                }
9005            }
9006
9007            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9008                if (DEBUG_DEXOPT) {
9009                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9010                }
9011                numberOfPackagesSkipped++;
9012                continue;
9013            }
9014
9015            if (DEBUG_DEXOPT) {
9016                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9017                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9018            }
9019
9020            if (showDialog) {
9021                try {
9022                    ActivityManager.getService().showBootMessage(
9023                            mContext.getResources().getString(R.string.android_upgrading_apk,
9024                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9025                } catch (RemoteException e) {
9026                }
9027                synchronized (mPackages) {
9028                    mDexOptDialogShown = true;
9029                }
9030            }
9031
9032            int pkgCompilationReason = compilationReason;
9033            if (useProfileForDexopt) {
9034                // Use background dexopt mode to try and use the profile. Note that this does not
9035                // guarantee usage of the profile.
9036                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9037            }
9038
9039            // checkProfiles is false to avoid merging profiles during boot which
9040            // might interfere with background compilation (b/28612421).
9041            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9042            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9043            // trade-off worth doing to save boot time work.
9044            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9045            if (compilationReason == REASON_FIRST_BOOT) {
9046                // TODO: This doesn't cover the upgrade case, we should check for this too.
9047                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9048            }
9049            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9050                    pkg.packageName,
9051                    pkgCompilationReason,
9052                    dexoptFlags));
9053
9054            switch (primaryDexOptStaus) {
9055                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9056                    numberOfPackagesOptimized++;
9057                    break;
9058                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9059                    numberOfPackagesSkipped++;
9060                    break;
9061                case PackageDexOptimizer.DEX_OPT_FAILED:
9062                    numberOfPackagesFailed++;
9063                    break;
9064                default:
9065                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9066                    break;
9067            }
9068        }
9069
9070        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9071                numberOfPackagesFailed };
9072    }
9073
9074    @Override
9075    public void notifyPackageUse(String packageName, int reason) {
9076        synchronized (mPackages) {
9077            final int callingUid = Binder.getCallingUid();
9078            final int callingUserId = UserHandle.getUserId(callingUid);
9079            if (getInstantAppPackageName(callingUid) != null) {
9080                if (!isCallerSameApp(packageName, callingUid)) {
9081                    return;
9082                }
9083            } else {
9084                if (isInstantApp(packageName, callingUserId)) {
9085                    return;
9086                }
9087            }
9088            notifyPackageUseLocked(packageName, reason);
9089        }
9090    }
9091
9092    @GuardedBy("mPackages")
9093    private void notifyPackageUseLocked(String packageName, int reason) {
9094        final PackageParser.Package p = mPackages.get(packageName);
9095        if (p == null) {
9096            return;
9097        }
9098        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9099    }
9100
9101    @Override
9102    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9103            List<String> classPaths, String loaderIsa) {
9104        int userId = UserHandle.getCallingUserId();
9105        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9106        if (ai == null) {
9107            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9108                + loadingPackageName + ", user=" + userId);
9109            return;
9110        }
9111        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9112    }
9113
9114    @Override
9115    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9116            IDexModuleRegisterCallback callback) {
9117        int userId = UserHandle.getCallingUserId();
9118        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9119        DexManager.RegisterDexModuleResult result;
9120        if (ai == null) {
9121            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9122                     " calling user. package=" + packageName + ", user=" + userId);
9123            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9124        } else {
9125            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9126        }
9127
9128        if (callback != null) {
9129            mHandler.post(() -> {
9130                try {
9131                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9132                } catch (RemoteException e) {
9133                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9134                }
9135            });
9136        }
9137    }
9138
9139    /**
9140     * Ask the package manager to perform a dex-opt with the given compiler filter.
9141     *
9142     * Note: exposed only for the shell command to allow moving packages explicitly to a
9143     *       definite state.
9144     */
9145    @Override
9146    public boolean performDexOptMode(String packageName,
9147            boolean checkProfiles, String targetCompilerFilter, boolean force,
9148            boolean bootComplete, String splitName) {
9149        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9150                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9151                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9152        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9153                targetCompilerFilter, splitName, flags));
9154    }
9155
9156    /**
9157     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9158     * secondary dex files belonging to the given package.
9159     *
9160     * Note: exposed only for the shell command to allow moving packages explicitly to a
9161     *       definite state.
9162     */
9163    @Override
9164    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9165            boolean force) {
9166        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9167                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9168                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9169                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9170        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9171    }
9172
9173    /*package*/ boolean performDexOpt(DexoptOptions options) {
9174        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9175            return false;
9176        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9177            return false;
9178        }
9179
9180        if (options.isDexoptOnlySecondaryDex()) {
9181            return mDexManager.dexoptSecondaryDex(options);
9182        } else {
9183            int dexoptStatus = performDexOptWithStatus(options);
9184            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9185        }
9186    }
9187
9188    /**
9189     * Perform dexopt on the given package and return one of following result:
9190     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9191     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9192     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9193     */
9194    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9195        return performDexOptTraced(options);
9196    }
9197
9198    private int performDexOptTraced(DexoptOptions options) {
9199        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9200        try {
9201            return performDexOptInternal(options);
9202        } finally {
9203            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9204        }
9205    }
9206
9207    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9208    // if the package can now be considered up to date for the given filter.
9209    private int performDexOptInternal(DexoptOptions options) {
9210        PackageParser.Package p;
9211        synchronized (mPackages) {
9212            p = mPackages.get(options.getPackageName());
9213            if (p == null) {
9214                // Package could not be found. Report failure.
9215                return PackageDexOptimizer.DEX_OPT_FAILED;
9216            }
9217            mPackageUsage.maybeWriteAsync(mPackages);
9218            mCompilerStats.maybeWriteAsync();
9219        }
9220        long callingId = Binder.clearCallingIdentity();
9221        try {
9222            synchronized (mInstallLock) {
9223                return performDexOptInternalWithDependenciesLI(p, options);
9224            }
9225        } finally {
9226            Binder.restoreCallingIdentity(callingId);
9227        }
9228    }
9229
9230    public ArraySet<String> getOptimizablePackages() {
9231        ArraySet<String> pkgs = new ArraySet<String>();
9232        synchronized (mPackages) {
9233            for (PackageParser.Package p : mPackages.values()) {
9234                if (PackageDexOptimizer.canOptimizePackage(p)) {
9235                    pkgs.add(p.packageName);
9236                }
9237            }
9238        }
9239        return pkgs;
9240    }
9241
9242    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9243            DexoptOptions options) {
9244        // Select the dex optimizer based on the force parameter.
9245        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9246        //       allocate an object here.
9247        PackageDexOptimizer pdo = options.isForce()
9248                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9249                : mPackageDexOptimizer;
9250
9251        // Dexopt all dependencies first. Note: we ignore the return value and march on
9252        // on errors.
9253        // Note that we are going to call performDexOpt on those libraries as many times as
9254        // they are referenced in packages. When we do a batch of performDexOpt (for example
9255        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9256        // and the first package that uses the library will dexopt it. The
9257        // others will see that the compiled code for the library is up to date.
9258        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9259        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9260        if (!deps.isEmpty()) {
9261            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9262                    options.getCompilationReason(), options.getCompilerFilter(),
9263                    options.getSplitName(),
9264                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9265            for (PackageParser.Package depPackage : deps) {
9266                // TODO: Analyze and investigate if we (should) profile libraries.
9267                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9268                        getOrCreateCompilerPackageStats(depPackage),
9269                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9270            }
9271        }
9272        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9273                getOrCreateCompilerPackageStats(p),
9274                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9275    }
9276
9277    /**
9278     * Reconcile the information we have about the secondary dex files belonging to
9279     * {@code packagName} and the actual dex files. For all dex files that were
9280     * deleted, update the internal records and delete the generated oat files.
9281     */
9282    @Override
9283    public void reconcileSecondaryDexFiles(String packageName) {
9284        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9285            return;
9286        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9287            return;
9288        }
9289        mDexManager.reconcileSecondaryDexFiles(packageName);
9290    }
9291
9292    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9293    // a reference there.
9294    /*package*/ DexManager getDexManager() {
9295        return mDexManager;
9296    }
9297
9298    /**
9299     * Execute the background dexopt job immediately.
9300     */
9301    @Override
9302    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9303        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9304            return false;
9305        }
9306        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9307    }
9308
9309    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9310        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9311                || p.usesStaticLibraries != null) {
9312            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9313            Set<String> collectedNames = new HashSet<>();
9314            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9315
9316            retValue.remove(p);
9317
9318            return retValue;
9319        } else {
9320            return Collections.emptyList();
9321        }
9322    }
9323
9324    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9325            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9326        if (!collectedNames.contains(p.packageName)) {
9327            collectedNames.add(p.packageName);
9328            collected.add(p);
9329
9330            if (p.usesLibraries != null) {
9331                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9332                        null, collected, collectedNames);
9333            }
9334            if (p.usesOptionalLibraries != null) {
9335                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9336                        null, collected, collectedNames);
9337            }
9338            if (p.usesStaticLibraries != null) {
9339                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9340                        p.usesStaticLibrariesVersions, collected, collectedNames);
9341            }
9342        }
9343    }
9344
9345    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9346            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9347        final int libNameCount = libs.size();
9348        for (int i = 0; i < libNameCount; i++) {
9349            String libName = libs.get(i);
9350            long version = (versions != null && versions.length == libNameCount)
9351                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9352            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9353            if (libPkg != null) {
9354                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9355            }
9356        }
9357    }
9358
9359    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9360        synchronized (mPackages) {
9361            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9362            if (libEntry != null) {
9363                return mPackages.get(libEntry.apk);
9364            }
9365            return null;
9366        }
9367    }
9368
9369    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9370        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9371        if (versionedLib == null) {
9372            return null;
9373        }
9374        return versionedLib.get(version);
9375    }
9376
9377    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9378        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9379                pkg.staticSharedLibName);
9380        if (versionedLib == null) {
9381            return null;
9382        }
9383        long previousLibVersion = -1;
9384        final int versionCount = versionedLib.size();
9385        for (int i = 0; i < versionCount; i++) {
9386            final long libVersion = versionedLib.keyAt(i);
9387            if (libVersion < pkg.staticSharedLibVersion) {
9388                previousLibVersion = Math.max(previousLibVersion, libVersion);
9389            }
9390        }
9391        if (previousLibVersion >= 0) {
9392            return versionedLib.get(previousLibVersion);
9393        }
9394        return null;
9395    }
9396
9397    public void shutdown() {
9398        mPackageUsage.writeNow(mPackages);
9399        mCompilerStats.writeNow();
9400        mDexManager.writePackageDexUsageNow();
9401    }
9402
9403    @Override
9404    public void dumpProfiles(String packageName) {
9405        PackageParser.Package pkg;
9406        synchronized (mPackages) {
9407            pkg = mPackages.get(packageName);
9408            if (pkg == null) {
9409                throw new IllegalArgumentException("Unknown package: " + packageName);
9410            }
9411        }
9412        /* Only the shell, root, or the app user should be able to dump profiles. */
9413        int callingUid = Binder.getCallingUid();
9414        if (callingUid != Process.SHELL_UID &&
9415            callingUid != Process.ROOT_UID &&
9416            callingUid != pkg.applicationInfo.uid) {
9417            throw new SecurityException("dumpProfiles");
9418        }
9419
9420        synchronized (mInstallLock) {
9421            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9422            mArtManagerService.dumpProfiles(pkg);
9423            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9424        }
9425    }
9426
9427    @Override
9428    public void forceDexOpt(String packageName) {
9429        enforceSystemOrRoot("forceDexOpt");
9430
9431        PackageParser.Package pkg;
9432        synchronized (mPackages) {
9433            pkg = mPackages.get(packageName);
9434            if (pkg == null) {
9435                throw new IllegalArgumentException("Unknown package: " + packageName);
9436            }
9437        }
9438
9439        synchronized (mInstallLock) {
9440            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9441
9442            // Whoever is calling forceDexOpt wants a compiled package.
9443            // Don't use profiles since that may cause compilation to be skipped.
9444            final int res = performDexOptInternalWithDependenciesLI(
9445                    pkg,
9446                    new DexoptOptions(packageName,
9447                            getDefaultCompilerFilter(),
9448                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9449
9450            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9451            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9452                throw new IllegalStateException("Failed to dexopt: " + res);
9453            }
9454        }
9455    }
9456
9457    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9458        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9459            Slog.w(TAG, "Unable to update from " + oldPkg.name
9460                    + " to " + newPkg.packageName
9461                    + ": old package not in system partition");
9462            return false;
9463        } else if (mPackages.get(oldPkg.name) != null) {
9464            Slog.w(TAG, "Unable to update from " + oldPkg.name
9465                    + " to " + newPkg.packageName
9466                    + ": old package still exists");
9467            return false;
9468        }
9469        return true;
9470    }
9471
9472    void removeCodePathLI(File codePath) {
9473        if (codePath.isDirectory()) {
9474            try {
9475                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9476            } catch (InstallerException e) {
9477                Slog.w(TAG, "Failed to remove code path", e);
9478            }
9479        } else {
9480            codePath.delete();
9481        }
9482    }
9483
9484    private int[] resolveUserIds(int userId) {
9485        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9486    }
9487
9488    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9489        if (pkg == null) {
9490            Slog.wtf(TAG, "Package was null!", new Throwable());
9491            return;
9492        }
9493        clearAppDataLeafLIF(pkg, userId, flags);
9494        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9495        for (int i = 0; i < childCount; i++) {
9496            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9497        }
9498
9499        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9500    }
9501
9502    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9503        final PackageSetting ps;
9504        synchronized (mPackages) {
9505            ps = mSettings.mPackages.get(pkg.packageName);
9506        }
9507        for (int realUserId : resolveUserIds(userId)) {
9508            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9509            try {
9510                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9511                        ceDataInode);
9512            } catch (InstallerException e) {
9513                Slog.w(TAG, String.valueOf(e));
9514            }
9515        }
9516    }
9517
9518    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9519        if (pkg == null) {
9520            Slog.wtf(TAG, "Package was null!", new Throwable());
9521            return;
9522        }
9523        destroyAppDataLeafLIF(pkg, userId, flags);
9524        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9525        for (int i = 0; i < childCount; i++) {
9526            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9527        }
9528    }
9529
9530    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9531        final PackageSetting ps;
9532        synchronized (mPackages) {
9533            ps = mSettings.mPackages.get(pkg.packageName);
9534        }
9535        for (int realUserId : resolveUserIds(userId)) {
9536            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9537            try {
9538                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9539                        ceDataInode);
9540            } catch (InstallerException e) {
9541                Slog.w(TAG, String.valueOf(e));
9542            }
9543            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9544        }
9545    }
9546
9547    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9548        if (pkg == null) {
9549            Slog.wtf(TAG, "Package was null!", new Throwable());
9550            return;
9551        }
9552        destroyAppProfilesLeafLIF(pkg);
9553        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9554        for (int i = 0; i < childCount; i++) {
9555            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9556        }
9557    }
9558
9559    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9560        try {
9561            mInstaller.destroyAppProfiles(pkg.packageName);
9562        } catch (InstallerException e) {
9563            Slog.w(TAG, String.valueOf(e));
9564        }
9565    }
9566
9567    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9568        if (pkg == null) {
9569            Slog.wtf(TAG, "Package was null!", new Throwable());
9570            return;
9571        }
9572        mArtManagerService.clearAppProfiles(pkg);
9573        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9574        for (int i = 0; i < childCount; i++) {
9575            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9576        }
9577    }
9578
9579    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9580            long lastUpdateTime) {
9581        // Set parent install/update time
9582        PackageSetting ps = (PackageSetting) pkg.mExtras;
9583        if (ps != null) {
9584            ps.firstInstallTime = firstInstallTime;
9585            ps.lastUpdateTime = lastUpdateTime;
9586        }
9587        // Set children install/update time
9588        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9589        for (int i = 0; i < childCount; i++) {
9590            PackageParser.Package childPkg = pkg.childPackages.get(i);
9591            ps = (PackageSetting) childPkg.mExtras;
9592            if (ps != null) {
9593                ps.firstInstallTime = firstInstallTime;
9594                ps.lastUpdateTime = lastUpdateTime;
9595            }
9596        }
9597    }
9598
9599    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9600            SharedLibraryEntry file,
9601            PackageParser.Package changingLib) {
9602        if (file.path != null) {
9603            usesLibraryFiles.add(file.path);
9604            return;
9605        }
9606        PackageParser.Package p = mPackages.get(file.apk);
9607        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9608            // If we are doing this while in the middle of updating a library apk,
9609            // then we need to make sure to use that new apk for determining the
9610            // dependencies here.  (We haven't yet finished committing the new apk
9611            // to the package manager state.)
9612            if (p == null || p.packageName.equals(changingLib.packageName)) {
9613                p = changingLib;
9614            }
9615        }
9616        if (p != null) {
9617            usesLibraryFiles.addAll(p.getAllCodePaths());
9618            if (p.usesLibraryFiles != null) {
9619                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9620            }
9621        }
9622    }
9623
9624    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9625            PackageParser.Package changingLib) throws PackageManagerException {
9626        if (pkg == null) {
9627            return;
9628        }
9629        // The collection used here must maintain the order of addition (so
9630        // that libraries are searched in the correct order) and must have no
9631        // duplicates.
9632        Set<String> usesLibraryFiles = null;
9633        if (pkg.usesLibraries != null) {
9634            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9635                    null, null, pkg.packageName, changingLib, true,
9636                    pkg.applicationInfo.targetSdkVersion, null);
9637        }
9638        if (pkg.usesStaticLibraries != null) {
9639            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9640                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9641                    pkg.packageName, changingLib, true,
9642                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9643        }
9644        if (pkg.usesOptionalLibraries != null) {
9645            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9646                    null, null, pkg.packageName, changingLib, false,
9647                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9648        }
9649        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9650            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9651        } else {
9652            pkg.usesLibraryFiles = null;
9653        }
9654    }
9655
9656    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9657            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9658            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9659            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9660            throws PackageManagerException {
9661        final int libCount = requestedLibraries.size();
9662        for (int i = 0; i < libCount; i++) {
9663            final String libName = requestedLibraries.get(i);
9664            final long libVersion = requiredVersions != null ? requiredVersions[i]
9665                    : SharedLibraryInfo.VERSION_UNDEFINED;
9666            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9667            if (libEntry == null) {
9668                if (required) {
9669                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9670                            "Package " + packageName + " requires unavailable shared library "
9671                                    + libName + "; failing!");
9672                } else if (DEBUG_SHARED_LIBRARIES) {
9673                    Slog.i(TAG, "Package " + packageName
9674                            + " desires unavailable shared library "
9675                            + libName + "; ignoring!");
9676                }
9677            } else {
9678                if (requiredVersions != null && requiredCertDigests != null) {
9679                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9680                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9681                            "Package " + packageName + " requires unavailable static shared"
9682                                    + " library " + libName + " version "
9683                                    + libEntry.info.getLongVersion() + "; failing!");
9684                    }
9685
9686                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9687                    if (libPkg == null) {
9688                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9689                                "Package " + packageName + " requires unavailable static shared"
9690                                        + " library; failing!");
9691                    }
9692
9693                    final String[] expectedCertDigests = requiredCertDigests[i];
9694
9695
9696                    if (expectedCertDigests.length > 1) {
9697
9698                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9699                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9700                                ? PackageUtils.computeSignaturesSha256Digests(
9701                                libPkg.mSigningDetails.signatures)
9702                                : PackageUtils.computeSignaturesSha256Digests(
9703                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9704
9705                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9706                        // target O we don't parse the "additional-certificate" tags similarly
9707                        // how we only consider all certs only for apps targeting O (see above).
9708                        // Therefore, the size check is safe to make.
9709                        if (expectedCertDigests.length != libCertDigests.length) {
9710                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9711                                    "Package " + packageName + " requires differently signed" +
9712                                            " static shared library; failing!");
9713                        }
9714
9715                        // Use a predictable order as signature order may vary
9716                        Arrays.sort(libCertDigests);
9717                        Arrays.sort(expectedCertDigests);
9718
9719                        final int certCount = libCertDigests.length;
9720                        for (int j = 0; j < certCount; j++) {
9721                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9722                                throw new PackageManagerException(
9723                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9724                                        "Package " + packageName + " requires differently signed" +
9725                                                " static shared library; failing!");
9726                            }
9727                        }
9728                    } else {
9729
9730                        // lib signing cert could have rotated beyond the one expected, check to see
9731                        // if the new one has been blessed by the old
9732                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9733                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9734                            throw new PackageManagerException(
9735                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9736                                    "Package " + packageName + " requires differently signed" +
9737                                            " static shared library; failing!");
9738                        }
9739                    }
9740                }
9741
9742                if (outUsedLibraries == null) {
9743                    // Use LinkedHashSet to preserve the order of files added to
9744                    // usesLibraryFiles while eliminating duplicates.
9745                    outUsedLibraries = new LinkedHashSet<>();
9746                }
9747                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9748            }
9749        }
9750        return outUsedLibraries;
9751    }
9752
9753    private static boolean hasString(List<String> list, List<String> which) {
9754        if (list == null) {
9755            return false;
9756        }
9757        for (int i=list.size()-1; i>=0; i--) {
9758            for (int j=which.size()-1; j>=0; j--) {
9759                if (which.get(j).equals(list.get(i))) {
9760                    return true;
9761                }
9762            }
9763        }
9764        return false;
9765    }
9766
9767    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9768            PackageParser.Package changingPkg) {
9769        ArrayList<PackageParser.Package> res = null;
9770        for (PackageParser.Package pkg : mPackages.values()) {
9771            if (changingPkg != null
9772                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9773                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9774                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9775                            changingPkg.staticSharedLibName)) {
9776                return null;
9777            }
9778            if (res == null) {
9779                res = new ArrayList<>();
9780            }
9781            res.add(pkg);
9782            try {
9783                updateSharedLibrariesLPr(pkg, changingPkg);
9784            } catch (PackageManagerException e) {
9785                // If a system app update or an app and a required lib missing we
9786                // delete the package and for updated system apps keep the data as
9787                // it is better for the user to reinstall than to be in an limbo
9788                // state. Also libs disappearing under an app should never happen
9789                // - just in case.
9790                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9791                    final int flags = pkg.isUpdatedSystemApp()
9792                            ? PackageManager.DELETE_KEEP_DATA : 0;
9793                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9794                            flags , null, true, null);
9795                }
9796                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9797            }
9798        }
9799        return res;
9800    }
9801
9802    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9803            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9804            @Nullable UserHandle user) throws PackageManagerException {
9805        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9806        // If the package has children and this is the first dive in the function
9807        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9808        // whether all packages (parent and children) would be successfully scanned
9809        // before the actual scan since scanning mutates internal state and we want
9810        // to atomically install the package and its children.
9811        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9812            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9813                scanFlags |= SCAN_CHECK_ONLY;
9814            }
9815        } else {
9816            scanFlags &= ~SCAN_CHECK_ONLY;
9817        }
9818
9819        final PackageParser.Package scannedPkg;
9820        try {
9821            // Scan the parent
9822            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9823            // Scan the children
9824            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9825            for (int i = 0; i < childCount; i++) {
9826                PackageParser.Package childPkg = pkg.childPackages.get(i);
9827                scanPackageNewLI(childPkg, parseFlags,
9828                        scanFlags, currentTime, user);
9829            }
9830        } finally {
9831            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9832        }
9833
9834        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9835            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9836        }
9837
9838        return scannedPkg;
9839    }
9840
9841    /** The result of a package scan. */
9842    private static class ScanResult {
9843        /** Whether or not the package scan was successful */
9844        public final boolean success;
9845        /**
9846         * The final package settings. This may be the same object passed in
9847         * the {@link ScanRequest}, but, with modified values.
9848         */
9849        @Nullable public final PackageSetting pkgSetting;
9850        /** ABI code paths that have changed in the package scan */
9851        @Nullable public final List<String> changedAbiCodePath;
9852        public ScanResult(
9853                boolean success,
9854                @Nullable PackageSetting pkgSetting,
9855                @Nullable List<String> changedAbiCodePath) {
9856            this.success = success;
9857            this.pkgSetting = pkgSetting;
9858            this.changedAbiCodePath = changedAbiCodePath;
9859        }
9860    }
9861
9862    /** A package to be scanned */
9863    private static class ScanRequest {
9864        /** The parsed package */
9865        @NonNull public final PackageParser.Package pkg;
9866        /** Shared user settings, if the package has a shared user */
9867        @Nullable public final SharedUserSetting sharedUserSetting;
9868        /**
9869         * Package settings of the currently installed version.
9870         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9871         * during scan.
9872         */
9873        @Nullable public final PackageSetting pkgSetting;
9874        /** A copy of the settings for the currently installed version */
9875        @Nullable public final PackageSetting oldPkgSetting;
9876        /** Package settings for the disabled version on the /system partition */
9877        @Nullable public final PackageSetting disabledPkgSetting;
9878        /** Package settings for the installed version under its original package name */
9879        @Nullable public final PackageSetting originalPkgSetting;
9880        /** The real package name of a renamed application */
9881        @Nullable public final String realPkgName;
9882        public final @ParseFlags int parseFlags;
9883        public final @ScanFlags int scanFlags;
9884        /** The user for which the package is being scanned */
9885        @Nullable public final UserHandle user;
9886        /** Whether or not the platform package is being scanned */
9887        public final boolean isPlatformPackage;
9888        public ScanRequest(
9889                @NonNull PackageParser.Package pkg,
9890                @Nullable SharedUserSetting sharedUserSetting,
9891                @Nullable PackageSetting pkgSetting,
9892                @Nullable PackageSetting disabledPkgSetting,
9893                @Nullable PackageSetting originalPkgSetting,
9894                @Nullable String realPkgName,
9895                @ParseFlags int parseFlags,
9896                @ScanFlags int scanFlags,
9897                boolean isPlatformPackage,
9898                @Nullable UserHandle user) {
9899            this.pkg = pkg;
9900            this.pkgSetting = pkgSetting;
9901            this.sharedUserSetting = sharedUserSetting;
9902            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9903            this.disabledPkgSetting = disabledPkgSetting;
9904            this.originalPkgSetting = originalPkgSetting;
9905            this.realPkgName = realPkgName;
9906            this.parseFlags = parseFlags;
9907            this.scanFlags = scanFlags;
9908            this.isPlatformPackage = isPlatformPackage;
9909            this.user = user;
9910        }
9911    }
9912
9913    /**
9914     * Returns the actual scan flags depending upon the state of the other settings.
9915     * <p>Updated system applications will not have the following flags set
9916     * by default and need to be adjusted after the fact:
9917     * <ul>
9918     * <li>{@link #SCAN_AS_SYSTEM}</li>
9919     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9920     * <li>{@link #SCAN_AS_OEM}</li>
9921     * <li>{@link #SCAN_AS_VENDOR}</li>
9922     * <li>{@link #SCAN_AS_PRODUCT}</li>
9923     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9924     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9925     * </ul>
9926     */
9927    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9928            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9929            PackageParser.Package pkg) {
9930        if (disabledPkgSetting != null) {
9931            // updated system application, must at least have SCAN_AS_SYSTEM
9932            scanFlags |= SCAN_AS_SYSTEM;
9933            if ((disabledPkgSetting.pkgPrivateFlags
9934                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9935                scanFlags |= SCAN_AS_PRIVILEGED;
9936            }
9937            if ((disabledPkgSetting.pkgPrivateFlags
9938                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9939                scanFlags |= SCAN_AS_OEM;
9940            }
9941            if ((disabledPkgSetting.pkgPrivateFlags
9942                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9943                scanFlags |= SCAN_AS_VENDOR;
9944            }
9945            if ((disabledPkgSetting.pkgPrivateFlags
9946                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9947                scanFlags |= SCAN_AS_PRODUCT;
9948            }
9949        }
9950        if (pkgSetting != null) {
9951            final int userId = ((user == null) ? 0 : user.getIdentifier());
9952            if (pkgSetting.getInstantApp(userId)) {
9953                scanFlags |= SCAN_AS_INSTANT_APP;
9954            }
9955            if (pkgSetting.getVirtulalPreload(userId)) {
9956                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9957            }
9958        }
9959
9960        // Scan as privileged apps that share a user with a priv-app.
9961        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9962                && (pkg.mSharedUserId != null)) {
9963            SharedUserSetting sharedUserSetting = null;
9964            try {
9965                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9966            } catch (PackageManagerException ignore) {}
9967            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9968                // Exempt SharedUsers signed with the platform key.
9969                // TODO(b/72378145) Fix this exemption. Force signature apps
9970                // to whitelist their privileged permissions just like other
9971                // priv-apps.
9972                synchronized (mPackages) {
9973                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9974                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9975                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9976                        scanFlags |= SCAN_AS_PRIVILEGED;
9977                    }
9978                }
9979            }
9980        }
9981
9982        return scanFlags;
9983    }
9984
9985    // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
9986    // the results / removing app data needs to be moved up a level to the callers of this
9987    // method. Also, we need to solve the problem of potentially creating a new shared user
9988    // setting. That can probably be done later and patch things up after the fact.
9989    @GuardedBy("mInstallLock")
9990    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9991            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9992            @Nullable UserHandle user) throws PackageManagerException {
9993
9994        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9995        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9996        if (realPkgName != null) {
9997            ensurePackageRenamed(pkg, renamedPkgName);
9998        }
9999        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10000        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10001        final PackageSetting disabledPkgSetting =
10002                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10003
10004        if (mTransferedPackages.contains(pkg.packageName)) {
10005            Slog.w(TAG, "Package " + pkg.packageName
10006                    + " was transferred to another, but its .apk remains");
10007        }
10008
10009        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10010        synchronized (mPackages) {
10011            applyPolicy(pkg, parseFlags, scanFlags);
10012            assertPackageIsValid(pkg, parseFlags, scanFlags);
10013
10014            SharedUserSetting sharedUserSetting = null;
10015            if (pkg.mSharedUserId != null) {
10016                // SIDE EFFECTS; may potentially allocate a new shared user
10017                sharedUserSetting = mSettings.getSharedUserLPw(
10018                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10019                if (DEBUG_PACKAGE_SCANNING) {
10020                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10021                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10022                                + " (uid=" + sharedUserSetting.userId + "):"
10023                                + " packages=" + sharedUserSetting.packages);
10024                }
10025            }
10026
10027            boolean scanSucceeded = false;
10028            try {
10029                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10030                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10031                        (pkg == mPlatformPackage), user);
10032                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10033                if (result.success) {
10034                    commitScanResultsLocked(request, result);
10035                }
10036                scanSucceeded = true;
10037            } finally {
10038                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10039                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10040                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10041                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10042                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10043                  }
10044            }
10045        }
10046        return pkg;
10047    }
10048
10049    /**
10050     * Commits the package scan and modifies system state.
10051     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10052     * of committing the package, leaving the system in an inconsistent state.
10053     * This needs to be fixed so, once we get to this point, no errors are
10054     * possible and the system is not left in an inconsistent state.
10055     */
10056    @GuardedBy("mPackages")
10057    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10058            throws PackageManagerException {
10059        final PackageParser.Package pkg = request.pkg;
10060        final @ParseFlags int parseFlags = request.parseFlags;
10061        final @ScanFlags int scanFlags = request.scanFlags;
10062        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10063        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10064        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10065        final UserHandle user = request.user;
10066        final String realPkgName = request.realPkgName;
10067        final PackageSetting pkgSetting = result.pkgSetting;
10068        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10069        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10070
10071        if (newPkgSettingCreated) {
10072            if (originalPkgSetting != null) {
10073                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10074            }
10075            // THROWS: when we can't allocate a user id. add call to check if there's
10076            // enough space to ensure we won't throw; otherwise, don't modify state
10077            mSettings.addUserToSettingLPw(pkgSetting);
10078
10079            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10080                mTransferedPackages.add(originalPkgSetting.name);
10081            }
10082        }
10083        // TODO(toddke): Consider a method specifically for modifying the Package object
10084        // post scan; or, moving this stuff out of the Package object since it has nothing
10085        // to do with the package on disk.
10086        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10087        // for creating the application ID. If we did this earlier, we would be saving the
10088        // correct ID.
10089        pkg.applicationInfo.uid = pkgSetting.appId;
10090
10091        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10092
10093        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10094            mTransferedPackages.add(pkg.packageName);
10095        }
10096
10097        // THROWS: when requested libraries that can't be found. it only changes
10098        // the state of the passed in pkg object, so, move to the top of the method
10099        // and allow it to abort
10100        if ((scanFlags & SCAN_BOOTING) == 0
10101                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10102            // Check all shared libraries and map to their actual file path.
10103            // We only do this here for apps not on a system dir, because those
10104            // are the only ones that can fail an install due to this.  We
10105            // will take care of the system apps by updating all of their
10106            // library paths after the scan is done. Also during the initial
10107            // scan don't update any libs as we do this wholesale after all
10108            // apps are scanned to avoid dependency based scanning.
10109            updateSharedLibrariesLPr(pkg, null);
10110        }
10111
10112        // All versions of a static shared library are referenced with the same
10113        // package name. Internally, we use a synthetic package name to allow
10114        // multiple versions of the same shared library to be installed. So,
10115        // we need to generate the synthetic package name of the latest shared
10116        // library in order to compare signatures.
10117        PackageSetting signatureCheckPs = pkgSetting;
10118        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10119            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10120            if (libraryEntry != null) {
10121                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10122            }
10123        }
10124
10125        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10126        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10127            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10128                // We just determined the app is signed correctly, so bring
10129                // over the latest parsed certs.
10130                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10131            } else {
10132                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10133                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10134                            "Package " + pkg.packageName + " upgrade keys do not match the "
10135                                    + "previously installed version");
10136                } else {
10137                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10138                    String msg = "System package " + pkg.packageName
10139                            + " signature changed; retaining data.";
10140                    reportSettingsProblem(Log.WARN, msg);
10141                }
10142            }
10143        } else {
10144            try {
10145                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10146                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10147                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10148                        pkg.mSigningDetails, compareCompat, compareRecover);
10149                // The new KeySets will be re-added later in the scanning process.
10150                if (compatMatch) {
10151                    synchronized (mPackages) {
10152                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10153                    }
10154                }
10155                // We just determined the app is signed correctly, so bring
10156                // over the latest parsed certs.
10157                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10158
10159
10160                // if this is is a sharedUser, check to see if the new package is signed by a newer
10161                // signing certificate than the existing one, and if so, copy over the new details
10162                if (signatureCheckPs.sharedUser != null
10163                        && pkg.mSigningDetails.hasAncestor(
10164                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10165                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10166                }
10167            } catch (PackageManagerException e) {
10168                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10169                    throw e;
10170                }
10171                // The signature has changed, but this package is in the system
10172                // image...  let's recover!
10173                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10174                // However...  if this package is part of a shared user, but it
10175                // doesn't match the signature of the shared user, let's fail.
10176                // What this means is that you can't change the signatures
10177                // associated with an overall shared user, which doesn't seem all
10178                // that unreasonable.
10179                if (signatureCheckPs.sharedUser != null) {
10180                    if (compareSignatures(
10181                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10182                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10183                        throw new PackageManagerException(
10184                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10185                                "Signature mismatch for shared user: "
10186                                        + pkgSetting.sharedUser);
10187                    }
10188                }
10189                // File a report about this.
10190                String msg = "System package " + pkg.packageName
10191                        + " signature changed; retaining data.";
10192                reportSettingsProblem(Log.WARN, msg);
10193            } catch (IllegalArgumentException e) {
10194
10195                // should never happen: certs matched when checking, but not when comparing
10196                // old to new for sharedUser
10197                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10198                        "Signing certificates comparison made on incomparable signing details"
10199                        + " but somehow passed verifySignatures!");
10200            }
10201        }
10202
10203        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10204            // This package wants to adopt ownership of permissions from
10205            // another package.
10206            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10207                final String origName = pkg.mAdoptPermissions.get(i);
10208                final PackageSetting orig = mSettings.getPackageLPr(origName);
10209                if (orig != null) {
10210                    if (verifyPackageUpdateLPr(orig, pkg)) {
10211                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10212                                + pkg.packageName);
10213                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10214                    }
10215                }
10216            }
10217        }
10218
10219        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10220            for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
10221                final String codePathString = changedAbiCodePath.get(i);
10222                try {
10223                    mInstaller.rmdex(codePathString,
10224                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10225                } catch (InstallerException ignored) {
10226                }
10227            }
10228        }
10229
10230        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10231            if (oldPkgSetting != null) {
10232                synchronized (mPackages) {
10233                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10234                }
10235            }
10236        } else {
10237            final int userId = user == null ? 0 : user.getIdentifier();
10238            // Modify state for the given package setting
10239            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10240                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10241            if (pkgSetting.getInstantApp(userId)) {
10242                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10243            }
10244        }
10245    }
10246
10247    /**
10248     * Returns the "real" name of the package.
10249     * <p>This may differ from the package's actual name if the application has already
10250     * been installed under one of this package's original names.
10251     */
10252    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10253            @Nullable String renamedPkgName) {
10254        if (isPackageRenamed(pkg, renamedPkgName)) {
10255            return pkg.mRealPackage;
10256        }
10257        return null;
10258    }
10259
10260    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10261    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10262            @Nullable String renamedPkgName) {
10263        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10264    }
10265
10266    /**
10267     * Returns the original package setting.
10268     * <p>A package can migrate its name during an update. In this scenario, a package
10269     * designates a set of names that it considers as one of its original names.
10270     * <p>An original package must be signed identically and it must have the same
10271     * shared user [if any].
10272     */
10273    @GuardedBy("mPackages")
10274    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10275            @Nullable String renamedPkgName) {
10276        if (!isPackageRenamed(pkg, renamedPkgName)) {
10277            return null;
10278        }
10279        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10280            final PackageSetting originalPs =
10281                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10282            if (originalPs != null) {
10283                // the package is already installed under its original name...
10284                // but, should we use it?
10285                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10286                    // the new package is incompatible with the original
10287                    continue;
10288                } else if (originalPs.sharedUser != null) {
10289                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10290                        // the shared user id is incompatible with the original
10291                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10292                                + " to " + pkg.packageName + ": old uid "
10293                                + originalPs.sharedUser.name
10294                                + " differs from " + pkg.mSharedUserId);
10295                        continue;
10296                    }
10297                    // TODO: Add case when shared user id is added [b/28144775]
10298                } else {
10299                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10300                            + pkg.packageName + " to old name " + originalPs.name);
10301                }
10302                return originalPs;
10303            }
10304        }
10305        return null;
10306    }
10307
10308    /**
10309     * Renames the package if it was installed under a different name.
10310     * <p>When we've already installed the package under an original name, update
10311     * the new package so we can continue to have the old name.
10312     */
10313    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10314            @NonNull String renamedPackageName) {
10315        if (pkg.mOriginalPackages == null
10316                || !pkg.mOriginalPackages.contains(renamedPackageName)
10317                || pkg.packageName.equals(renamedPackageName)) {
10318            return;
10319        }
10320        pkg.setPackageName(renamedPackageName);
10321    }
10322
10323    /**
10324     * Just scans the package without any side effects.
10325     * <p>Not entirely true at the moment. There is still one side effect -- this
10326     * method potentially modifies a live {@link PackageSetting} object representing
10327     * the package being scanned. This will be resolved in the future.
10328     *
10329     * @param request Information about the package to be scanned
10330     * @param isUnderFactoryTest Whether or not the device is under factory test
10331     * @param currentTime The current time, in millis
10332     * @return The results of the scan
10333     */
10334    @GuardedBy("mInstallLock")
10335    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10336            boolean isUnderFactoryTest, long currentTime)
10337                    throws PackageManagerException {
10338        final PackageParser.Package pkg = request.pkg;
10339        PackageSetting pkgSetting = request.pkgSetting;
10340        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10341        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10342        final @ParseFlags int parseFlags = request.parseFlags;
10343        final @ScanFlags int scanFlags = request.scanFlags;
10344        final String realPkgName = request.realPkgName;
10345        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10346        final UserHandle user = request.user;
10347        final boolean isPlatformPackage = request.isPlatformPackage;
10348
10349        List<String> changedAbiCodePath = null;
10350
10351        if (DEBUG_PACKAGE_SCANNING) {
10352            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10353                Log.d(TAG, "Scanning package " + pkg.packageName);
10354        }
10355
10356        if (Build.IS_DEBUGGABLE &&
10357                pkg.isPrivileged() &&
10358                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
10359            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10360        }
10361
10362        // Initialize package source and resource directories
10363        final File scanFile = new File(pkg.codePath);
10364        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10365        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10366
10367        // We keep references to the derived CPU Abis from settings in oder to reuse
10368        // them in the case where we're not upgrading or booting for the first time.
10369        String primaryCpuAbiFromSettings = null;
10370        String secondaryCpuAbiFromSettings = null;
10371        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10372
10373        if (!needToDeriveAbi) {
10374            if (pkgSetting != null) {
10375                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10376                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10377            } else {
10378                // Re-scanning a system package after uninstalling updates; need to derive ABI
10379                needToDeriveAbi = true;
10380            }
10381        }
10382
10383        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10384            PackageManagerService.reportSettingsProblem(Log.WARN,
10385                    "Package " + pkg.packageName + " shared user changed from "
10386                            + (pkgSetting.sharedUser != null
10387                            ? pkgSetting.sharedUser.name : "<nothing>")
10388                            + " to "
10389                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10390                            + "; replacing with new");
10391            pkgSetting = null;
10392        }
10393
10394        String[] usesStaticLibraries = null;
10395        if (pkg.usesStaticLibraries != null) {
10396            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10397            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10398        }
10399        final boolean createNewPackage = (pkgSetting == null);
10400        if (createNewPackage) {
10401            final String parentPackageName = (pkg.parentPackage != null)
10402                    ? pkg.parentPackage.packageName : null;
10403            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10404            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10405            // REMOVE SharedUserSetting from method; update in a separate call
10406            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10407                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10408                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10409                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10410                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10411                    user, true /*allowInstall*/, instantApp, virtualPreload,
10412                    parentPackageName, pkg.getChildPackageNames(),
10413                    UserManagerService.getInstance(), usesStaticLibraries,
10414                    pkg.usesStaticLibrariesVersions);
10415        } else {
10416            // REMOVE SharedUserSetting from method; update in a separate call.
10417            //
10418            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10419            // secondaryCpuAbi are not known at this point so we always update them
10420            // to null here, only to reset them at a later point.
10421            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10422                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10423                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10424                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10425                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10426                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10427        }
10428        if (createNewPackage && originalPkgSetting != null) {
10429            // This is the initial transition from the original package, so,
10430            // fix up the new package's name now. We must do this after looking
10431            // up the package under its new name, so getPackageLP takes care of
10432            // fiddling things correctly.
10433            pkg.setPackageName(originalPkgSetting.name);
10434
10435            // File a report about this.
10436            String msg = "New package " + pkgSetting.realName
10437                    + " renamed to replace old package " + pkgSetting.name;
10438            reportSettingsProblem(Log.WARN, msg);
10439        }
10440
10441        final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
10442        // for existing packages, change the install state; but, only if it's explicitly specified
10443        if (!createNewPackage) {
10444            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10445            final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
10446            setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
10447        }
10448
10449        if (disabledPkgSetting != null) {
10450            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10451        }
10452
10453        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10454        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10455        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10456        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10457        // least restrictive selinux domain.
10458        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10459        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10460        // ensures that all packages continue to run in the same selinux domain.
10461        final int targetSdkVersion =
10462            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10463            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10464        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10465        // They currently can be if the sharedUser apps are signed with the platform key.
10466        final boolean isPrivileged = (sharedUserSetting != null) ?
10467            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10468
10469        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10470                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10471        pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
10472                userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
10473
10474        pkg.mExtras = pkgSetting;
10475        pkg.applicationInfo.processName = fixProcessName(
10476                pkg.applicationInfo.packageName,
10477                pkg.applicationInfo.processName);
10478
10479        if (!isPlatformPackage) {
10480            // Get all of our default paths setup
10481            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10482        }
10483
10484        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10485
10486        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10487            if (needToDeriveAbi) {
10488                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10489                final boolean extractNativeLibs = !pkg.isLibrary();
10490                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10491                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10492
10493                // Some system apps still use directory structure for native libraries
10494                // in which case we might end up not detecting abi solely based on apk
10495                // structure. Try to detect abi based on directory structure.
10496                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10497                        pkg.applicationInfo.primaryCpuAbi == null) {
10498                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10499                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10500                }
10501            } else {
10502                // This is not a first boot or an upgrade, don't bother deriving the
10503                // ABI during the scan. Instead, trust the value that was stored in the
10504                // package setting.
10505                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10506                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10507
10508                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10509
10510                if (DEBUG_ABI_SELECTION) {
10511                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10512                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10513                            pkg.applicationInfo.secondaryCpuAbi);
10514                }
10515            }
10516        } else {
10517            if ((scanFlags & SCAN_MOVE) != 0) {
10518                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10519                // but we already have this packages package info in the PackageSetting. We just
10520                // use that and derive the native library path based on the new codepath.
10521                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10522                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10523            }
10524
10525            // Set native library paths again. For moves, the path will be updated based on the
10526            // ABIs we've determined above. For non-moves, the path will be updated based on the
10527            // ABIs we determined during compilation, but the path will depend on the final
10528            // package path (after the rename away from the stage path).
10529            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10530        }
10531
10532        // This is a special case for the "system" package, where the ABI is
10533        // dictated by the zygote configuration (and init.rc). We should keep track
10534        // of this ABI so that we can deal with "normal" applications that run under
10535        // the same UID correctly.
10536        if (isPlatformPackage) {
10537            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10538                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10539        }
10540
10541        // If there's a mismatch between the abi-override in the package setting
10542        // and the abiOverride specified for the install. Warn about this because we
10543        // would've already compiled the app without taking the package setting into
10544        // account.
10545        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10546            if (cpuAbiOverride == null && pkg.packageName != null) {
10547                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10548                        " for package " + pkg.packageName);
10549            }
10550        }
10551
10552        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10553        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10554        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10555
10556        // Copy the derived override back to the parsed package, so that we can
10557        // update the package settings accordingly.
10558        pkg.cpuAbiOverride = cpuAbiOverride;
10559
10560        if (DEBUG_ABI_SELECTION) {
10561            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10562                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10563                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10564        }
10565
10566        // Push the derived path down into PackageSettings so we know what to
10567        // clean up at uninstall time.
10568        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10569
10570        if (DEBUG_ABI_SELECTION) {
10571            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10572                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10573                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10574        }
10575
10576        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10577            // We don't do this here during boot because we can do it all
10578            // at once after scanning all existing packages.
10579            //
10580            // We also do this *before* we perform dexopt on this package, so that
10581            // we can avoid redundant dexopts, and also to make sure we've got the
10582            // code and package path correct.
10583            changedAbiCodePath =
10584                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10585        }
10586
10587        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10588                android.Manifest.permission.FACTORY_TEST)) {
10589            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10590        }
10591
10592        if (isSystemApp(pkg)) {
10593            pkgSetting.isOrphaned = true;
10594        }
10595
10596        // Take care of first install / last update times.
10597        final long scanFileTime = getLastModifiedTime(pkg);
10598        if (currentTime != 0) {
10599            if (pkgSetting.firstInstallTime == 0) {
10600                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10601            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10602                pkgSetting.lastUpdateTime = currentTime;
10603            }
10604        } else if (pkgSetting.firstInstallTime == 0) {
10605            // We need *something*.  Take time time stamp of the file.
10606            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10607        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10608            if (scanFileTime != pkgSetting.timeStamp) {
10609                // A package on the system image has changed; consider this
10610                // to be an update.
10611                pkgSetting.lastUpdateTime = scanFileTime;
10612            }
10613        }
10614        pkgSetting.setTimeStamp(scanFileTime);
10615
10616        pkgSetting.pkg = pkg;
10617        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10618        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10619            pkgSetting.versionCode = pkg.getLongVersionCode();
10620        }
10621        // Update volume if needed
10622        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10623        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10624            Slog.i(PackageManagerService.TAG,
10625                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10626                    + " package " + pkg.packageName
10627                    + " volume from " + pkgSetting.volumeUuid
10628                    + " to " + volumeUuid);
10629            pkgSetting.volumeUuid = volumeUuid;
10630        }
10631
10632        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10633    }
10634
10635    /**
10636     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10637     */
10638    private static boolean apkHasCode(String fileName) {
10639        StrictJarFile jarFile = null;
10640        try {
10641            jarFile = new StrictJarFile(fileName,
10642                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10643            return jarFile.findEntry("classes.dex") != null;
10644        } catch (IOException ignore) {
10645        } finally {
10646            try {
10647                if (jarFile != null) {
10648                    jarFile.close();
10649                }
10650            } catch (IOException ignore) {}
10651        }
10652        return false;
10653    }
10654
10655    /**
10656     * Enforces code policy for the package. This ensures that if an APK has
10657     * declared hasCode="true" in its manifest that the APK actually contains
10658     * code.
10659     *
10660     * @throws PackageManagerException If bytecode could not be found when it should exist
10661     */
10662    private static void assertCodePolicy(PackageParser.Package pkg)
10663            throws PackageManagerException {
10664        final boolean shouldHaveCode =
10665                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10666        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10667            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10668                    "Package " + pkg.baseCodePath + " code is missing");
10669        }
10670
10671        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10672            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10673                final boolean splitShouldHaveCode =
10674                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10675                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10676                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10677                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10678                }
10679            }
10680        }
10681    }
10682
10683    /**
10684     * Applies policy to the parsed package based upon the given policy flags.
10685     * Ensures the package is in a good state.
10686     * <p>
10687     * Implementation detail: This method must NOT have any side effect. It would
10688     * ideally be static, but, it requires locks to read system state.
10689     */
10690    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10691            final @ScanFlags int scanFlags) {
10692        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10693            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10694            if (pkg.applicationInfo.isDirectBootAware()) {
10695                // we're direct boot aware; set for all components
10696                for (PackageParser.Service s : pkg.services) {
10697                    s.info.encryptionAware = s.info.directBootAware = true;
10698                }
10699                for (PackageParser.Provider p : pkg.providers) {
10700                    p.info.encryptionAware = p.info.directBootAware = true;
10701                }
10702                for (PackageParser.Activity a : pkg.activities) {
10703                    a.info.encryptionAware = a.info.directBootAware = true;
10704                }
10705                for (PackageParser.Activity r : pkg.receivers) {
10706                    r.info.encryptionAware = r.info.directBootAware = true;
10707                }
10708            }
10709            if (compressedFileExists(pkg.codePath)) {
10710                pkg.isStub = true;
10711            }
10712        } else {
10713            // non system apps can't be flagged as core
10714            pkg.coreApp = false;
10715            // clear flags not applicable to regular apps
10716            pkg.applicationInfo.flags &=
10717                    ~ApplicationInfo.FLAG_PERSISTENT;
10718            pkg.applicationInfo.privateFlags &=
10719                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10720            pkg.applicationInfo.privateFlags &=
10721                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10722            // cap permission priorities
10723            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10724                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10725                    pkg.permissionGroups.get(i).info.priority = 0;
10726                }
10727            }
10728        }
10729        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10730            // clear protected broadcasts
10731            pkg.protectedBroadcasts = null;
10732            // ignore export request for single user receivers
10733            if (pkg.receivers != null) {
10734                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10735                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10736                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10737                        receiver.info.exported = false;
10738                    }
10739                }
10740            }
10741            // ignore export request for single user services
10742            if (pkg.services != null) {
10743                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10744                    final PackageParser.Service service = pkg.services.get(i);
10745                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10746                        service.info.exported = false;
10747                    }
10748                }
10749            }
10750            // ignore export request for single user providers
10751            if (pkg.providers != null) {
10752                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10753                    final PackageParser.Provider provider = pkg.providers.get(i);
10754                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10755                        provider.info.exported = false;
10756                    }
10757                }
10758            }
10759        }
10760
10761        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10762            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10763        }
10764
10765        if ((scanFlags & SCAN_AS_OEM) != 0) {
10766            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10767        }
10768
10769        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10770            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10771        }
10772
10773        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10774            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10775        }
10776
10777        if (!isSystemApp(pkg)) {
10778            // Only system apps can use these features.
10779            pkg.mOriginalPackages = null;
10780            pkg.mRealPackage = null;
10781            pkg.mAdoptPermissions = null;
10782        }
10783    }
10784
10785    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10786            throws PackageManagerException {
10787        if (object == null) {
10788            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10789        }
10790        return object;
10791    }
10792
10793    /**
10794     * Asserts the parsed package is valid according to the given policy. If the
10795     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10796     * <p>
10797     * Implementation detail: This method must NOT have any side effects. It would
10798     * ideally be static, but, it requires locks to read system state.
10799     *
10800     * @throws PackageManagerException If the package fails any of the validation checks
10801     */
10802    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10803            final @ScanFlags int scanFlags)
10804                    throws PackageManagerException {
10805        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10806            assertCodePolicy(pkg);
10807        }
10808
10809        if (pkg.applicationInfo.getCodePath() == null ||
10810                pkg.applicationInfo.getResourcePath() == null) {
10811            // Bail out. The resource and code paths haven't been set.
10812            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10813                    "Code and resource paths haven't been set correctly");
10814        }
10815
10816        // Make sure we're not adding any bogus keyset info
10817        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10818        ksms.assertScannedPackageValid(pkg);
10819
10820        synchronized (mPackages) {
10821            // The special "android" package can only be defined once
10822            if (pkg.packageName.equals("android")) {
10823                if (mAndroidApplication != null) {
10824                    Slog.w(TAG, "*************************************************");
10825                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10826                    Slog.w(TAG, " codePath=" + pkg.codePath);
10827                    Slog.w(TAG, "*************************************************");
10828                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10829                            "Core android package being redefined.  Skipping.");
10830                }
10831            }
10832
10833            // A package name must be unique; don't allow duplicates
10834            if (mPackages.containsKey(pkg.packageName)) {
10835                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10836                        "Application package " + pkg.packageName
10837                        + " already installed.  Skipping duplicate.");
10838            }
10839
10840            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10841                // Static libs have a synthetic package name containing the version
10842                // but we still want the base name to be unique.
10843                if (mPackages.containsKey(pkg.manifestPackageName)) {
10844                    throw new PackageManagerException(
10845                            "Duplicate static shared lib provider package");
10846                }
10847
10848                // Static shared libraries should have at least O target SDK
10849                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10850                    throw new PackageManagerException(
10851                            "Packages declaring static-shared libs must target O SDK or higher");
10852                }
10853
10854                // Package declaring static a shared lib cannot be instant apps
10855                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10856                    throw new PackageManagerException(
10857                            "Packages declaring static-shared libs cannot be instant apps");
10858                }
10859
10860                // Package declaring static a shared lib cannot be renamed since the package
10861                // name is synthetic and apps can't code around package manager internals.
10862                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10863                    throw new PackageManagerException(
10864                            "Packages declaring static-shared libs cannot be renamed");
10865                }
10866
10867                // Package declaring static a shared lib cannot declare child packages
10868                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10869                    throw new PackageManagerException(
10870                            "Packages declaring static-shared libs cannot have child packages");
10871                }
10872
10873                // Package declaring static a shared lib cannot declare dynamic libs
10874                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10875                    throw new PackageManagerException(
10876                            "Packages declaring static-shared libs cannot declare dynamic libs");
10877                }
10878
10879                // Package declaring static a shared lib cannot declare shared users
10880                if (pkg.mSharedUserId != null) {
10881                    throw new PackageManagerException(
10882                            "Packages declaring static-shared libs cannot declare shared users");
10883                }
10884
10885                // Static shared libs cannot declare activities
10886                if (!pkg.activities.isEmpty()) {
10887                    throw new PackageManagerException(
10888                            "Static shared libs cannot declare activities");
10889                }
10890
10891                // Static shared libs cannot declare services
10892                if (!pkg.services.isEmpty()) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare services");
10895                }
10896
10897                // Static shared libs cannot declare providers
10898                if (!pkg.providers.isEmpty()) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot declare content providers");
10901                }
10902
10903                // Static shared libs cannot declare receivers
10904                if (!pkg.receivers.isEmpty()) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot declare broadcast receivers");
10907                }
10908
10909                // Static shared libs cannot declare permission groups
10910                if (!pkg.permissionGroups.isEmpty()) {
10911                    throw new PackageManagerException(
10912                            "Static shared libs cannot declare permission groups");
10913                }
10914
10915                // Static shared libs cannot declare permissions
10916                if (!pkg.permissions.isEmpty()) {
10917                    throw new PackageManagerException(
10918                            "Static shared libs cannot declare permissions");
10919                }
10920
10921                // Static shared libs cannot declare protected broadcasts
10922                if (pkg.protectedBroadcasts != null) {
10923                    throw new PackageManagerException(
10924                            "Static shared libs cannot declare protected broadcasts");
10925                }
10926
10927                // Static shared libs cannot be overlay targets
10928                if (pkg.mOverlayTarget != null) {
10929                    throw new PackageManagerException(
10930                            "Static shared libs cannot be overlay targets");
10931                }
10932
10933                // The version codes must be ordered as lib versions
10934                long minVersionCode = Long.MIN_VALUE;
10935                long maxVersionCode = Long.MAX_VALUE;
10936
10937                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10938                        pkg.staticSharedLibName);
10939                if (versionedLib != null) {
10940                    final int versionCount = versionedLib.size();
10941                    for (int i = 0; i < versionCount; i++) {
10942                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10943                        final long libVersionCode = libInfo.getDeclaringPackage()
10944                                .getLongVersionCode();
10945                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10946                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10947                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10948                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10949                        } else {
10950                            minVersionCode = maxVersionCode = libVersionCode;
10951                            break;
10952                        }
10953                    }
10954                }
10955                if (pkg.getLongVersionCode() < minVersionCode
10956                        || pkg.getLongVersionCode() > maxVersionCode) {
10957                    throw new PackageManagerException("Static shared"
10958                            + " lib version codes must be ordered as lib versions");
10959                }
10960            }
10961
10962            // Only privileged apps and updated privileged apps can add child packages.
10963            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10964                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10965                    throw new PackageManagerException("Only privileged apps can add child "
10966                            + "packages. Ignoring package " + pkg.packageName);
10967                }
10968                final int childCount = pkg.childPackages.size();
10969                for (int i = 0; i < childCount; i++) {
10970                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10971                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10972                            childPkg.packageName)) {
10973                        throw new PackageManagerException("Can't override child of "
10974                                + "another disabled app. Ignoring package " + pkg.packageName);
10975                    }
10976                }
10977            }
10978
10979            // If we're only installing presumed-existing packages, require that the
10980            // scanned APK is both already known and at the path previously established
10981            // for it.  Previously unknown packages we pick up normally, but if we have an
10982            // a priori expectation about this package's install presence, enforce it.
10983            // With a singular exception for new system packages. When an OTA contains
10984            // a new system package, we allow the codepath to change from a system location
10985            // to the user-installed location. If we don't allow this change, any newer,
10986            // user-installed version of the application will be ignored.
10987            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10988                if (mExpectingBetter.containsKey(pkg.packageName)) {
10989                    logCriticalInfo(Log.WARN,
10990                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10991                } else {
10992                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10993                    if (known != null) {
10994                        if (DEBUG_PACKAGE_SCANNING) {
10995                            Log.d(TAG, "Examining " + pkg.codePath
10996                                    + " and requiring known paths " + known.codePathString
10997                                    + " & " + known.resourcePathString);
10998                        }
10999                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11000                                || !pkg.applicationInfo.getResourcePath().equals(
11001                                        known.resourcePathString)) {
11002                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11003                                    "Application package " + pkg.packageName
11004                                    + " found at " + pkg.applicationInfo.getCodePath()
11005                                    + " but expected at " + known.codePathString
11006                                    + "; ignoring.");
11007                        }
11008                    } else {
11009                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11010                                "Application package " + pkg.packageName
11011                                + " not found; ignoring.");
11012                    }
11013                }
11014            }
11015
11016            // Verify that this new package doesn't have any content providers
11017            // that conflict with existing packages.  Only do this if the
11018            // package isn't already installed, since we don't want to break
11019            // things that are installed.
11020            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11021                final int N = pkg.providers.size();
11022                int i;
11023                for (i=0; i<N; i++) {
11024                    PackageParser.Provider p = pkg.providers.get(i);
11025                    if (p.info.authority != null) {
11026                        String names[] = p.info.authority.split(";");
11027                        for (int j = 0; j < names.length; j++) {
11028                            if (mProvidersByAuthority.containsKey(names[j])) {
11029                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11030                                final String otherPackageName =
11031                                        ((other != null && other.getComponentName() != null) ?
11032                                                other.getComponentName().getPackageName() : "?");
11033                                throw new PackageManagerException(
11034                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11035                                        "Can't install because provider name " + names[j]
11036                                                + " (in package " + pkg.applicationInfo.packageName
11037                                                + ") is already used by " + otherPackageName);
11038                            }
11039                        }
11040                    }
11041                }
11042            }
11043
11044            // Verify that packages sharing a user with a privileged app are marked as privileged.
11045            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11046                SharedUserSetting sharedUserSetting = null;
11047                try {
11048                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11049                } catch (PackageManagerException ignore) {}
11050                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11051                    // Exempt SharedUsers signed with the platform key.
11052                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11053                    if ((platformPkgSetting.signatures.mSigningDetails
11054                            != PackageParser.SigningDetails.UNKNOWN)
11055                            && (compareSignatures(
11056                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11057                                    pkg.mSigningDetails.signatures)
11058                                            != PackageManager.SIGNATURE_MATCH)) {
11059                        throw new PackageManagerException("Apps that share a user with a " +
11060                                "privileged app must themselves be marked as privileged. " +
11061                                pkg.packageName + " shares privileged user " +
11062                                pkg.mSharedUserId + ".");
11063                    }
11064                }
11065            }
11066
11067            // Apply policies specific for runtime resource overlays (RROs).
11068            if (pkg.mOverlayTarget != null) {
11069                // System overlays have some restrictions on their use of the 'static' state.
11070                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11071                    // We are scanning a system overlay. This can be the first scan of the
11072                    // system/vendor/oem partition, or an update to the system overlay.
11073                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11074                        // This must be an update to a system overlay.
11075                        final PackageSetting previousPkg = assertNotNull(
11076                                mSettings.getPackageLPr(pkg.packageName),
11077                                "previous package state not present");
11078
11079                        // Static overlays cannot be updated.
11080                        if (previousPkg.pkg.mOverlayIsStatic) {
11081                            throw new PackageManagerException("Overlay " + pkg.packageName +
11082                                    " is static and cannot be upgraded.");
11083                        // Non-static overlays cannot be converted to static overlays.
11084                        } else if (pkg.mOverlayIsStatic) {
11085                            throw new PackageManagerException("Overlay " + pkg.packageName +
11086                                    " cannot be upgraded into a static overlay.");
11087                        }
11088                    }
11089                } else {
11090                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11091                    if (pkg.mOverlayIsStatic) {
11092                        throw new PackageManagerException("Overlay " + pkg.packageName +
11093                                " is static but not pre-installed.");
11094                    }
11095
11096                    // The only case where we allow installation of a non-system overlay is when
11097                    // its signature is signed with the platform certificate.
11098                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11099                    if ((platformPkgSetting.signatures.mSigningDetails
11100                            != PackageParser.SigningDetails.UNKNOWN)
11101                            && (compareSignatures(
11102                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11103                                    pkg.mSigningDetails.signatures)
11104                                            != PackageManager.SIGNATURE_MATCH)) {
11105                        throw new PackageManagerException("Overlay " + pkg.packageName +
11106                                " must be signed with the platform certificate.");
11107                    }
11108                }
11109            }
11110        }
11111    }
11112
11113    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11114            int type, String declaringPackageName, long declaringVersionCode) {
11115        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11116        if (versionedLib == null) {
11117            versionedLib = new LongSparseArray<>();
11118            mSharedLibraries.put(name, versionedLib);
11119            if (type == SharedLibraryInfo.TYPE_STATIC) {
11120                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11121            }
11122        } else if (versionedLib.indexOfKey(version) >= 0) {
11123            return false;
11124        }
11125        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11126                version, type, declaringPackageName, declaringVersionCode);
11127        versionedLib.put(version, libEntry);
11128        return true;
11129    }
11130
11131    private boolean removeSharedLibraryLPw(String name, long version) {
11132        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11133        if (versionedLib == null) {
11134            return false;
11135        }
11136        final int libIdx = versionedLib.indexOfKey(version);
11137        if (libIdx < 0) {
11138            return false;
11139        }
11140        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11141        versionedLib.remove(version);
11142        if (versionedLib.size() <= 0) {
11143            mSharedLibraries.remove(name);
11144            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11145                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11146                        .getPackageName());
11147            }
11148        }
11149        return true;
11150    }
11151
11152    /**
11153     * Adds a scanned package to the system. When this method is finished, the package will
11154     * be available for query, resolution, etc...
11155     */
11156    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11157            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11158        final String pkgName = pkg.packageName;
11159        if (mCustomResolverComponentName != null &&
11160                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11161            setUpCustomResolverActivity(pkg);
11162        }
11163
11164        if (pkg.packageName.equals("android")) {
11165            synchronized (mPackages) {
11166                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11167                    // Set up information for our fall-back user intent resolution activity.
11168                    mPlatformPackage = pkg;
11169                    pkg.mVersionCode = mSdkVersion;
11170                    pkg.mVersionCodeMajor = 0;
11171                    mAndroidApplication = pkg.applicationInfo;
11172                    if (!mResolverReplaced) {
11173                        mResolveActivity.applicationInfo = mAndroidApplication;
11174                        mResolveActivity.name = ResolverActivity.class.getName();
11175                        mResolveActivity.packageName = mAndroidApplication.packageName;
11176                        mResolveActivity.processName = "system:ui";
11177                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11178                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11179                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11180                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11181                        mResolveActivity.exported = true;
11182                        mResolveActivity.enabled = true;
11183                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11184                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11185                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11186                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11187                                | ActivityInfo.CONFIG_ORIENTATION
11188                                | ActivityInfo.CONFIG_KEYBOARD
11189                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11190                        mResolveInfo.activityInfo = mResolveActivity;
11191                        mResolveInfo.priority = 0;
11192                        mResolveInfo.preferredOrder = 0;
11193                        mResolveInfo.match = 0;
11194                        mResolveComponentName = new ComponentName(
11195                                mAndroidApplication.packageName, mResolveActivity.name);
11196                    }
11197                }
11198            }
11199        }
11200
11201        ArrayList<PackageParser.Package> clientLibPkgs = null;
11202        // writer
11203        synchronized (mPackages) {
11204            boolean hasStaticSharedLibs = false;
11205
11206            // Any app can add new static shared libraries
11207            if (pkg.staticSharedLibName != null) {
11208                // Static shared libs don't allow renaming as they have synthetic package
11209                // names to allow install of multiple versions, so use name from manifest.
11210                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11211                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11212                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11213                    hasStaticSharedLibs = true;
11214                } else {
11215                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11216                                + pkg.staticSharedLibName + " already exists; skipping");
11217                }
11218                // Static shared libs cannot be updated once installed since they
11219                // use synthetic package name which includes the version code, so
11220                // not need to update other packages's shared lib dependencies.
11221            }
11222
11223            if (!hasStaticSharedLibs
11224                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11225                // Only system apps can add new dynamic shared libraries.
11226                if (pkg.libraryNames != null) {
11227                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11228                        String name = pkg.libraryNames.get(i);
11229                        boolean allowed = false;
11230                        if (pkg.isUpdatedSystemApp()) {
11231                            // New library entries can only be added through the
11232                            // system image.  This is important to get rid of a lot
11233                            // of nasty edge cases: for example if we allowed a non-
11234                            // system update of the app to add a library, then uninstalling
11235                            // the update would make the library go away, and assumptions
11236                            // we made such as through app install filtering would now
11237                            // have allowed apps on the device which aren't compatible
11238                            // with it.  Better to just have the restriction here, be
11239                            // conservative, and create many fewer cases that can negatively
11240                            // impact the user experience.
11241                            final PackageSetting sysPs = mSettings
11242                                    .getDisabledSystemPkgLPr(pkg.packageName);
11243                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11244                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11245                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11246                                        allowed = true;
11247                                        break;
11248                                    }
11249                                }
11250                            }
11251                        } else {
11252                            allowed = true;
11253                        }
11254                        if (allowed) {
11255                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11256                                    SharedLibraryInfo.VERSION_UNDEFINED,
11257                                    SharedLibraryInfo.TYPE_DYNAMIC,
11258                                    pkg.packageName, pkg.getLongVersionCode())) {
11259                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11260                                        + name + " already exists; skipping");
11261                            }
11262                        } else {
11263                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11264                                    + name + " that is not declared on system image; skipping");
11265                        }
11266                    }
11267
11268                    if ((scanFlags & SCAN_BOOTING) == 0) {
11269                        // If we are not booting, we need to update any applications
11270                        // that are clients of our shared library.  If we are booting,
11271                        // this will all be done once the scan is complete.
11272                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11273                    }
11274                }
11275            }
11276        }
11277
11278        if ((scanFlags & SCAN_BOOTING) != 0) {
11279            // No apps can run during boot scan, so they don't need to be frozen
11280        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11281            // Caller asked to not kill app, so it's probably not frozen
11282        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11283            // Caller asked us to ignore frozen check for some reason; they
11284            // probably didn't know the package name
11285        } else {
11286            // We're doing major surgery on this package, so it better be frozen
11287            // right now to keep it from launching
11288            checkPackageFrozen(pkgName);
11289        }
11290
11291        // Also need to kill any apps that are dependent on the library.
11292        if (clientLibPkgs != null) {
11293            for (int i=0; i<clientLibPkgs.size(); i++) {
11294                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11295                killApplication(clientPkg.applicationInfo.packageName,
11296                        clientPkg.applicationInfo.uid, "update lib");
11297            }
11298        }
11299
11300        // writer
11301        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11302
11303        synchronized (mPackages) {
11304            // We don't expect installation to fail beyond this point
11305
11306            // Add the new setting to mSettings
11307            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11308            // Add the new setting to mPackages
11309            mPackages.put(pkg.applicationInfo.packageName, pkg);
11310            // Make sure we don't accidentally delete its data.
11311            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11312            while (iter.hasNext()) {
11313                PackageCleanItem item = iter.next();
11314                if (pkgName.equals(item.packageName)) {
11315                    iter.remove();
11316                }
11317            }
11318
11319            // Add the package's KeySets to the global KeySetManagerService
11320            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11321            ksms.addScannedPackageLPw(pkg);
11322
11323            int N = pkg.providers.size();
11324            StringBuilder r = null;
11325            int i;
11326            for (i=0; i<N; i++) {
11327                PackageParser.Provider p = pkg.providers.get(i);
11328                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11329                        p.info.processName);
11330                mProviders.addProvider(p);
11331                p.syncable = p.info.isSyncable;
11332                if (p.info.authority != null) {
11333                    String names[] = p.info.authority.split(";");
11334                    p.info.authority = null;
11335                    for (int j = 0; j < names.length; j++) {
11336                        if (j == 1 && p.syncable) {
11337                            // We only want the first authority for a provider to possibly be
11338                            // syncable, so if we already added this provider using a different
11339                            // authority clear the syncable flag. We copy the provider before
11340                            // changing it because the mProviders object contains a reference
11341                            // to a provider that we don't want to change.
11342                            // Only do this for the second authority since the resulting provider
11343                            // object can be the same for all future authorities for this provider.
11344                            p = new PackageParser.Provider(p);
11345                            p.syncable = false;
11346                        }
11347                        if (!mProvidersByAuthority.containsKey(names[j])) {
11348                            mProvidersByAuthority.put(names[j], p);
11349                            if (p.info.authority == null) {
11350                                p.info.authority = names[j];
11351                            } else {
11352                                p.info.authority = p.info.authority + ";" + names[j];
11353                            }
11354                            if (DEBUG_PACKAGE_SCANNING) {
11355                                if (chatty)
11356                                    Log.d(TAG, "Registered content provider: " + names[j]
11357                                            + ", className = " + p.info.name + ", isSyncable = "
11358                                            + p.info.isSyncable);
11359                            }
11360                        } else {
11361                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11362                            Slog.w(TAG, "Skipping provider name " + names[j] +
11363                                    " (in package " + pkg.applicationInfo.packageName +
11364                                    "): name already used by "
11365                                    + ((other != null && other.getComponentName() != null)
11366                                            ? other.getComponentName().getPackageName() : "?"));
11367                        }
11368                    }
11369                }
11370                if (chatty) {
11371                    if (r == null) {
11372                        r = new StringBuilder(256);
11373                    } else {
11374                        r.append(' ');
11375                    }
11376                    r.append(p.info.name);
11377                }
11378            }
11379            if (r != null) {
11380                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11381            }
11382
11383            N = pkg.services.size();
11384            r = null;
11385            for (i=0; i<N; i++) {
11386                PackageParser.Service s = pkg.services.get(i);
11387                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11388                        s.info.processName);
11389                mServices.addService(s);
11390                if (chatty) {
11391                    if (r == null) {
11392                        r = new StringBuilder(256);
11393                    } else {
11394                        r.append(' ');
11395                    }
11396                    r.append(s.info.name);
11397                }
11398            }
11399            if (r != null) {
11400                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11401            }
11402
11403            N = pkg.receivers.size();
11404            r = null;
11405            for (i=0; i<N; i++) {
11406                PackageParser.Activity a = pkg.receivers.get(i);
11407                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11408                        a.info.processName);
11409                mReceivers.addActivity(a, "receiver");
11410                if (chatty) {
11411                    if (r == null) {
11412                        r = new StringBuilder(256);
11413                    } else {
11414                        r.append(' ');
11415                    }
11416                    r.append(a.info.name);
11417                }
11418            }
11419            if (r != null) {
11420                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11421            }
11422
11423            N = pkg.activities.size();
11424            r = null;
11425            for (i=0; i<N; i++) {
11426                PackageParser.Activity a = pkg.activities.get(i);
11427                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11428                        a.info.processName);
11429                mActivities.addActivity(a, "activity");
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, "  Activities: " + r);
11441            }
11442
11443            // Don't allow ephemeral applications to define new permissions groups.
11444            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11445                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11446                        + " ignored: instant apps cannot define new permission groups.");
11447            } else {
11448                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11449            }
11450
11451            // Don't allow ephemeral applications to define new permissions.
11452            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11453                Slog.w(TAG, "Permissions from package " + pkg.packageName
11454                        + " ignored: instant apps cannot define new permissions.");
11455            } else {
11456                mPermissionManager.addAllPermissions(pkg, chatty);
11457            }
11458
11459            N = pkg.instrumentation.size();
11460            r = null;
11461            for (i=0; i<N; i++) {
11462                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11463                a.info.packageName = pkg.applicationInfo.packageName;
11464                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11465                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11466                a.info.splitNames = pkg.splitNames;
11467                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11468                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11469                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11470                a.info.dataDir = pkg.applicationInfo.dataDir;
11471                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11472                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11473                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11474                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11475                mInstrumentation.put(a.getComponentName(), a);
11476                if (chatty) {
11477                    if (r == null) {
11478                        r = new StringBuilder(256);
11479                    } else {
11480                        r.append(' ');
11481                    }
11482                    r.append(a.info.name);
11483                }
11484            }
11485            if (r != null) {
11486                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11487            }
11488
11489            if (pkg.protectedBroadcasts != null) {
11490                N = pkg.protectedBroadcasts.size();
11491                synchronized (mProtectedBroadcasts) {
11492                    for (i = 0; i < N; i++) {
11493                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11494                    }
11495                }
11496            }
11497        }
11498
11499        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11500    }
11501
11502    /**
11503     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11504     * is derived purely on the basis of the contents of {@code scanFile} and
11505     * {@code cpuAbiOverride}.
11506     *
11507     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11508     */
11509    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11510            boolean extractLibs)
11511                    throws PackageManagerException {
11512        // Give ourselves some initial paths; we'll come back for another
11513        // pass once we've determined ABI below.
11514        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11515
11516        // We would never need to extract libs for forward-locked and external packages,
11517        // since the container service will do it for us. We shouldn't attempt to
11518        // extract libs from system app when it was not updated.
11519        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11520                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11521            extractLibs = false;
11522        }
11523
11524        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11525        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11526
11527        NativeLibraryHelper.Handle handle = null;
11528        try {
11529            handle = NativeLibraryHelper.Handle.create(pkg);
11530            // TODO(multiArch): This can be null for apps that didn't go through the
11531            // usual installation process. We can calculate it again, like we
11532            // do during install time.
11533            //
11534            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11535            // unnecessary.
11536            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11537
11538            // Null out the abis so that they can be recalculated.
11539            pkg.applicationInfo.primaryCpuAbi = null;
11540            pkg.applicationInfo.secondaryCpuAbi = null;
11541            if (isMultiArch(pkg.applicationInfo)) {
11542                // Warn if we've set an abiOverride for multi-lib packages..
11543                // By definition, we need to copy both 32 and 64 bit libraries for
11544                // such packages.
11545                if (pkg.cpuAbiOverride != null
11546                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11547                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11548                }
11549
11550                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11551                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11552                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11553                    if (extractLibs) {
11554                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11555                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11556                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11557                                useIsaSpecificSubdirs);
11558                    } else {
11559                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11560                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11561                    }
11562                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11563                }
11564
11565                // Shared library native code should be in the APK zip aligned
11566                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11567                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11568                            "Shared library native lib extraction not supported");
11569                }
11570
11571                maybeThrowExceptionForMultiArchCopy(
11572                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11573
11574                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11575                    if (extractLibs) {
11576                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11577                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11578                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11579                                useIsaSpecificSubdirs);
11580                    } else {
11581                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11582                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11583                    }
11584                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11585                }
11586
11587                maybeThrowExceptionForMultiArchCopy(
11588                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11589
11590                if (abi64 >= 0) {
11591                    // Shared library native libs should be in the APK zip aligned
11592                    if (extractLibs && pkg.isLibrary()) {
11593                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11594                                "Shared library native lib extraction not supported");
11595                    }
11596                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11597                }
11598
11599                if (abi32 >= 0) {
11600                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11601                    if (abi64 >= 0) {
11602                        if (pkg.use32bitAbi) {
11603                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11604                            pkg.applicationInfo.primaryCpuAbi = abi;
11605                        } else {
11606                            pkg.applicationInfo.secondaryCpuAbi = abi;
11607                        }
11608                    } else {
11609                        pkg.applicationInfo.primaryCpuAbi = abi;
11610                    }
11611                }
11612            } else {
11613                String[] abiList = (cpuAbiOverride != null) ?
11614                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11615
11616                // Enable gross and lame hacks for apps that are built with old
11617                // SDK tools. We must scan their APKs for renderscript bitcode and
11618                // not launch them if it's present. Don't bother checking on devices
11619                // that don't have 64 bit support.
11620                boolean needsRenderScriptOverride = false;
11621                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11622                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11623                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11624                    needsRenderScriptOverride = true;
11625                }
11626
11627                final int copyRet;
11628                if (extractLibs) {
11629                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11630                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11631                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11632                } else {
11633                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11634                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11635                }
11636                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11637
11638                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11639                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11640                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11641                }
11642
11643                if (copyRet >= 0) {
11644                    // Shared libraries that have native libs must be multi-architecture
11645                    if (pkg.isLibrary()) {
11646                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11647                                "Shared library with native libs must be multiarch");
11648                    }
11649                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11650                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11651                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11652                } else if (needsRenderScriptOverride) {
11653                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11654                }
11655            }
11656        } catch (IOException ioe) {
11657            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11658        } finally {
11659            IoUtils.closeQuietly(handle);
11660        }
11661
11662        // Now that we've calculated the ABIs and determined if it's an internal app,
11663        // we will go ahead and populate the nativeLibraryPath.
11664        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11665    }
11666
11667    /**
11668     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11669     * i.e, so that all packages can be run inside a single process if required.
11670     *
11671     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11672     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11673     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11674     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11675     * updating a package that belongs to a shared user.
11676     *
11677     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11678     * adds unnecessary complexity.
11679     */
11680    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11681            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11682        List<String> changedAbiCodePath = null;
11683        String requiredInstructionSet = null;
11684        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11685            requiredInstructionSet = VMRuntime.getInstructionSet(
11686                     scannedPackage.applicationInfo.primaryCpuAbi);
11687        }
11688
11689        PackageSetting requirer = null;
11690        for (PackageSetting ps : packagesForUser) {
11691            // If packagesForUser contains scannedPackage, we skip it. This will happen
11692            // when scannedPackage is an update of an existing package. Without this check,
11693            // we will never be able to change the ABI of any package belonging to a shared
11694            // user, even if it's compatible with other packages.
11695            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11696                if (ps.primaryCpuAbiString == null) {
11697                    continue;
11698                }
11699
11700                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11701                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11702                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11703                    // this but there's not much we can do.
11704                    String errorMessage = "Instruction set mismatch, "
11705                            + ((requirer == null) ? "[caller]" : requirer)
11706                            + " requires " + requiredInstructionSet + " whereas " + ps
11707                            + " requires " + instructionSet;
11708                    Slog.w(TAG, errorMessage);
11709                }
11710
11711                if (requiredInstructionSet == null) {
11712                    requiredInstructionSet = instructionSet;
11713                    requirer = ps;
11714                }
11715            }
11716        }
11717
11718        if (requiredInstructionSet != null) {
11719            String adjustedAbi;
11720            if (requirer != null) {
11721                // requirer != null implies that either scannedPackage was null or that scannedPackage
11722                // did not require an ABI, in which case we have to adjust scannedPackage to match
11723                // the ABI of the set (which is the same as requirer's ABI)
11724                adjustedAbi = requirer.primaryCpuAbiString;
11725                if (scannedPackage != null) {
11726                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11727                }
11728            } else {
11729                // requirer == null implies that we're updating all ABIs in the set to
11730                // match scannedPackage.
11731                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11732            }
11733
11734            for (PackageSetting ps : packagesForUser) {
11735                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11736                    if (ps.primaryCpuAbiString != null) {
11737                        continue;
11738                    }
11739
11740                    ps.primaryCpuAbiString = adjustedAbi;
11741                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11742                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11743                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11744                        if (DEBUG_ABI_SELECTION) {
11745                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11746                                    + " (requirer="
11747                                    + (requirer != null ? requirer.pkg : "null")
11748                                    + ", scannedPackage="
11749                                    + (scannedPackage != null ? scannedPackage : "null")
11750                                    + ")");
11751                        }
11752                        if (changedAbiCodePath == null) {
11753                            changedAbiCodePath = new ArrayList<>();
11754                        }
11755                        changedAbiCodePath.add(ps.codePathString);
11756                    }
11757                }
11758            }
11759        }
11760        return changedAbiCodePath;
11761    }
11762
11763    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11764        synchronized (mPackages) {
11765            mResolverReplaced = true;
11766            // Set up information for custom user intent resolution activity.
11767            mResolveActivity.applicationInfo = pkg.applicationInfo;
11768            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11769            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11770            mResolveActivity.processName = pkg.applicationInfo.packageName;
11771            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11772            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11773                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11774            mResolveActivity.theme = 0;
11775            mResolveActivity.exported = true;
11776            mResolveActivity.enabled = true;
11777            mResolveInfo.activityInfo = mResolveActivity;
11778            mResolveInfo.priority = 0;
11779            mResolveInfo.preferredOrder = 0;
11780            mResolveInfo.match = 0;
11781            mResolveComponentName = mCustomResolverComponentName;
11782            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11783                    mResolveComponentName);
11784        }
11785    }
11786
11787    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11788        if (installerActivity == null) {
11789            if (DEBUG_INSTANT) {
11790                Slog.d(TAG, "Clear ephemeral installer activity");
11791            }
11792            mInstantAppInstallerActivity = null;
11793            return;
11794        }
11795
11796        if (DEBUG_INSTANT) {
11797            Slog.d(TAG, "Set ephemeral installer activity: "
11798                    + installerActivity.getComponentName());
11799        }
11800        // Set up information for ephemeral installer activity
11801        mInstantAppInstallerActivity = installerActivity;
11802        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11803                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11804        mInstantAppInstallerActivity.exported = true;
11805        mInstantAppInstallerActivity.enabled = true;
11806        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11807        mInstantAppInstallerInfo.priority = 1;
11808        mInstantAppInstallerInfo.preferredOrder = 1;
11809        mInstantAppInstallerInfo.isDefault = true;
11810        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11811                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11812    }
11813
11814    private static String calculateBundledApkRoot(final String codePathString) {
11815        final File codePath = new File(codePathString);
11816        final File codeRoot;
11817        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11818            codeRoot = Environment.getRootDirectory();
11819        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11820            codeRoot = Environment.getOemDirectory();
11821        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11822            codeRoot = Environment.getVendorDirectory();
11823        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11824            codeRoot = Environment.getOdmDirectory();
11825        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11826            codeRoot = Environment.getProductDirectory();
11827        } else {
11828            // Unrecognized code path; take its top real segment as the apk root:
11829            // e.g. /something/app/blah.apk => /something
11830            try {
11831                File f = codePath.getCanonicalFile();
11832                File parent = f.getParentFile();    // non-null because codePath is a file
11833                File tmp;
11834                while ((tmp = parent.getParentFile()) != null) {
11835                    f = parent;
11836                    parent = tmp;
11837                }
11838                codeRoot = f;
11839                Slog.w(TAG, "Unrecognized code path "
11840                        + codePath + " - using " + codeRoot);
11841            } catch (IOException e) {
11842                // Can't canonicalize the code path -- shenanigans?
11843                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11844                return Environment.getRootDirectory().getPath();
11845            }
11846        }
11847        return codeRoot.getPath();
11848    }
11849
11850    /**
11851     * Derive and set the location of native libraries for the given package,
11852     * which varies depending on where and how the package was installed.
11853     */
11854    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11855        final ApplicationInfo info = pkg.applicationInfo;
11856        final String codePath = pkg.codePath;
11857        final File codeFile = new File(codePath);
11858        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11859        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11860
11861        info.nativeLibraryRootDir = null;
11862        info.nativeLibraryRootRequiresIsa = false;
11863        info.nativeLibraryDir = null;
11864        info.secondaryNativeLibraryDir = null;
11865
11866        if (isApkFile(codeFile)) {
11867            // Monolithic install
11868            if (bundledApp) {
11869                // If "/system/lib64/apkname" exists, assume that is the per-package
11870                // native library directory to use; otherwise use "/system/lib/apkname".
11871                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11872                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11873                        getPrimaryInstructionSet(info));
11874
11875                // This is a bundled system app so choose the path based on the ABI.
11876                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11877                // is just the default path.
11878                final String apkName = deriveCodePathName(codePath);
11879                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11880                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11881                        apkName).getAbsolutePath();
11882
11883                if (info.secondaryCpuAbi != null) {
11884                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11885                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11886                            secondaryLibDir, apkName).getAbsolutePath();
11887                }
11888            } else if (asecApp) {
11889                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11890                        .getAbsolutePath();
11891            } else {
11892                final String apkName = deriveCodePathName(codePath);
11893                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11894                        .getAbsolutePath();
11895            }
11896
11897            info.nativeLibraryRootRequiresIsa = false;
11898            info.nativeLibraryDir = info.nativeLibraryRootDir;
11899        } else {
11900            // Cluster install
11901            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11902            info.nativeLibraryRootRequiresIsa = true;
11903
11904            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11905                    getPrimaryInstructionSet(info)).getAbsolutePath();
11906
11907            if (info.secondaryCpuAbi != null) {
11908                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11909                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11910            }
11911        }
11912    }
11913
11914    /**
11915     * Calculate the abis and roots for a bundled app. These can uniquely
11916     * be determined from the contents of the system partition, i.e whether
11917     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11918     * of this information, and instead assume that the system was built
11919     * sensibly.
11920     */
11921    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11922                                           PackageSetting pkgSetting) {
11923        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11924
11925        // If "/system/lib64/apkname" exists, assume that is the per-package
11926        // native library directory to use; otherwise use "/system/lib/apkname".
11927        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11928        setBundledAppAbi(pkg, apkRoot, apkName);
11929        // pkgSetting might be null during rescan following uninstall of updates
11930        // to a bundled app, so accommodate that possibility.  The settings in
11931        // that case will be established later from the parsed package.
11932        //
11933        // If the settings aren't null, sync them up with what we've just derived.
11934        // note that apkRoot isn't stored in the package settings.
11935        if (pkgSetting != null) {
11936            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11937            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11938        }
11939    }
11940
11941    /**
11942     * Deduces the ABI of a bundled app and sets the relevant fields on the
11943     * parsed pkg object.
11944     *
11945     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11946     *        under which system libraries are installed.
11947     * @param apkName the name of the installed package.
11948     */
11949    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11950        final File codeFile = new File(pkg.codePath);
11951
11952        final boolean has64BitLibs;
11953        final boolean has32BitLibs;
11954        if (isApkFile(codeFile)) {
11955            // Monolithic install
11956            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11957            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11958        } else {
11959            // Cluster install
11960            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11961            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11962                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11963                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11964                has64BitLibs = (new File(rootDir, isa)).exists();
11965            } else {
11966                has64BitLibs = false;
11967            }
11968            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11969                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11970                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11971                has32BitLibs = (new File(rootDir, isa)).exists();
11972            } else {
11973                has32BitLibs = false;
11974            }
11975        }
11976
11977        if (has64BitLibs && !has32BitLibs) {
11978            // The package has 64 bit libs, but not 32 bit libs. Its primary
11979            // ABI should be 64 bit. We can safely assume here that the bundled
11980            // native libraries correspond to the most preferred ABI in the list.
11981
11982            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11983            pkg.applicationInfo.secondaryCpuAbi = null;
11984        } else if (has32BitLibs && !has64BitLibs) {
11985            // The package has 32 bit libs but not 64 bit libs. Its primary
11986            // ABI should be 32 bit.
11987
11988            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11989            pkg.applicationInfo.secondaryCpuAbi = null;
11990        } else if (has32BitLibs && has64BitLibs) {
11991            // The application has both 64 and 32 bit bundled libraries. We check
11992            // here that the app declares multiArch support, and warn if it doesn't.
11993            //
11994            // We will be lenient here and record both ABIs. The primary will be the
11995            // ABI that's higher on the list, i.e, a device that's configured to prefer
11996            // 64 bit apps will see a 64 bit primary ABI,
11997
11998            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11999                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12000            }
12001
12002            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12003                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12004                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12005            } else {
12006                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12007                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12008            }
12009        } else {
12010            pkg.applicationInfo.primaryCpuAbi = null;
12011            pkg.applicationInfo.secondaryCpuAbi = null;
12012        }
12013    }
12014
12015    private void killApplication(String pkgName, int appId, String reason) {
12016        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12017    }
12018
12019    private void killApplication(String pkgName, int appId, int userId, String reason) {
12020        // Request the ActivityManager to kill the process(only for existing packages)
12021        // so that we do not end up in a confused state while the user is still using the older
12022        // version of the application while the new one gets installed.
12023        final long token = Binder.clearCallingIdentity();
12024        try {
12025            IActivityManager am = ActivityManager.getService();
12026            if (am != null) {
12027                try {
12028                    am.killApplication(pkgName, appId, userId, reason);
12029                } catch (RemoteException e) {
12030                }
12031            }
12032        } finally {
12033            Binder.restoreCallingIdentity(token);
12034        }
12035    }
12036
12037    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12038        // Remove the parent package setting
12039        PackageSetting ps = (PackageSetting) pkg.mExtras;
12040        if (ps != null) {
12041            removePackageLI(ps, chatty);
12042        }
12043        // Remove the child package setting
12044        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12045        for (int i = 0; i < childCount; i++) {
12046            PackageParser.Package childPkg = pkg.childPackages.get(i);
12047            ps = (PackageSetting) childPkg.mExtras;
12048            if (ps != null) {
12049                removePackageLI(ps, chatty);
12050            }
12051        }
12052    }
12053
12054    void removePackageLI(PackageSetting ps, boolean chatty) {
12055        if (DEBUG_INSTALL) {
12056            if (chatty)
12057                Log.d(TAG, "Removing package " + ps.name);
12058        }
12059
12060        // writer
12061        synchronized (mPackages) {
12062            mPackages.remove(ps.name);
12063            final PackageParser.Package pkg = ps.pkg;
12064            if (pkg != null) {
12065                cleanPackageDataStructuresLILPw(pkg, chatty);
12066            }
12067        }
12068    }
12069
12070    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12071        if (DEBUG_INSTALL) {
12072            if (chatty)
12073                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12074        }
12075
12076        // writer
12077        synchronized (mPackages) {
12078            // Remove the parent package
12079            mPackages.remove(pkg.applicationInfo.packageName);
12080            cleanPackageDataStructuresLILPw(pkg, chatty);
12081
12082            // Remove the child packages
12083            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12084            for (int i = 0; i < childCount; i++) {
12085                PackageParser.Package childPkg = pkg.childPackages.get(i);
12086                mPackages.remove(childPkg.applicationInfo.packageName);
12087                cleanPackageDataStructuresLILPw(childPkg, chatty);
12088            }
12089        }
12090    }
12091
12092    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12093        int N = pkg.providers.size();
12094        StringBuilder r = null;
12095        int i;
12096        for (i=0; i<N; i++) {
12097            PackageParser.Provider p = pkg.providers.get(i);
12098            mProviders.removeProvider(p);
12099            if (p.info.authority == null) {
12100
12101                /* There was another ContentProvider with this authority when
12102                 * this app was installed so this authority is null,
12103                 * Ignore it as we don't have to unregister the provider.
12104                 */
12105                continue;
12106            }
12107            String names[] = p.info.authority.split(";");
12108            for (int j = 0; j < names.length; j++) {
12109                if (mProvidersByAuthority.get(names[j]) == p) {
12110                    mProvidersByAuthority.remove(names[j]);
12111                    if (DEBUG_REMOVE) {
12112                        if (chatty)
12113                            Log.d(TAG, "Unregistered content provider: " + names[j]
12114                                    + ", className = " + p.info.name + ", isSyncable = "
12115                                    + p.info.isSyncable);
12116                    }
12117                }
12118            }
12119            if (DEBUG_REMOVE && chatty) {
12120                if (r == null) {
12121                    r = new StringBuilder(256);
12122                } else {
12123                    r.append(' ');
12124                }
12125                r.append(p.info.name);
12126            }
12127        }
12128        if (r != null) {
12129            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12130        }
12131
12132        N = pkg.services.size();
12133        r = null;
12134        for (i=0; i<N; i++) {
12135            PackageParser.Service s = pkg.services.get(i);
12136            mServices.removeService(s);
12137            if (chatty) {
12138                if (r == null) {
12139                    r = new StringBuilder(256);
12140                } else {
12141                    r.append(' ');
12142                }
12143                r.append(s.info.name);
12144            }
12145        }
12146        if (r != null) {
12147            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12148        }
12149
12150        N = pkg.receivers.size();
12151        r = null;
12152        for (i=0; i<N; i++) {
12153            PackageParser.Activity a = pkg.receivers.get(i);
12154            mReceivers.removeActivity(a, "receiver");
12155            if (DEBUG_REMOVE && chatty) {
12156                if (r == null) {
12157                    r = new StringBuilder(256);
12158                } else {
12159                    r.append(' ');
12160                }
12161                r.append(a.info.name);
12162            }
12163        }
12164        if (r != null) {
12165            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12166        }
12167
12168        N = pkg.activities.size();
12169        r = null;
12170        for (i=0; i<N; i++) {
12171            PackageParser.Activity a = pkg.activities.get(i);
12172            mActivities.removeActivity(a, "activity");
12173            if (DEBUG_REMOVE && chatty) {
12174                if (r == null) {
12175                    r = new StringBuilder(256);
12176                } else {
12177                    r.append(' ');
12178                }
12179                r.append(a.info.name);
12180            }
12181        }
12182        if (r != null) {
12183            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12184        }
12185
12186        mPermissionManager.removeAllPermissions(pkg, chatty);
12187
12188        N = pkg.instrumentation.size();
12189        r = null;
12190        for (i=0; i<N; i++) {
12191            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12192            mInstrumentation.remove(a.getComponentName());
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, "  Instrumentation: " + r);
12204        }
12205
12206        r = null;
12207        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12208            // Only system apps can hold shared libraries.
12209            if (pkg.libraryNames != null) {
12210                for (i = 0; i < pkg.libraryNames.size(); i++) {
12211                    String name = pkg.libraryNames.get(i);
12212                    if (removeSharedLibraryLPw(name, 0)) {
12213                        if (DEBUG_REMOVE && chatty) {
12214                            if (r == null) {
12215                                r = new StringBuilder(256);
12216                            } else {
12217                                r.append(' ');
12218                            }
12219                            r.append(name);
12220                        }
12221                    }
12222                }
12223            }
12224        }
12225
12226        r = null;
12227
12228        // Any package can hold static shared libraries.
12229        if (pkg.staticSharedLibName != null) {
12230            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12231                if (DEBUG_REMOVE && chatty) {
12232                    if (r == null) {
12233                        r = new StringBuilder(256);
12234                    } else {
12235                        r.append(' ');
12236                    }
12237                    r.append(pkg.staticSharedLibName);
12238                }
12239            }
12240        }
12241
12242        if (r != null) {
12243            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12244        }
12245    }
12246
12247
12248    final class ActivityIntentResolver
12249            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12250        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12251                boolean defaultOnly, int userId) {
12252            if (!sUserManager.exists(userId)) return null;
12253            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12254            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12255        }
12256
12257        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12258                int userId) {
12259            if (!sUserManager.exists(userId)) return null;
12260            mFlags = flags;
12261            return super.queryIntent(intent, resolvedType,
12262                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12263                    userId);
12264        }
12265
12266        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12267                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12268            if (!sUserManager.exists(userId)) return null;
12269            if (packageActivities == null) {
12270                return null;
12271            }
12272            mFlags = flags;
12273            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12274            final int N = packageActivities.size();
12275            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12276                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12277
12278            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12279            for (int i = 0; i < N; ++i) {
12280                intentFilters = packageActivities.get(i).intents;
12281                if (intentFilters != null && intentFilters.size() > 0) {
12282                    PackageParser.ActivityIntentInfo[] array =
12283                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12284                    intentFilters.toArray(array);
12285                    listCut.add(array);
12286                }
12287            }
12288            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12289        }
12290
12291        /**
12292         * Finds a privileged activity that matches the specified activity names.
12293         */
12294        private PackageParser.Activity findMatchingActivity(
12295                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12296            for (PackageParser.Activity sysActivity : activityList) {
12297                if (sysActivity.info.name.equals(activityInfo.name)) {
12298                    return sysActivity;
12299                }
12300                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12301                    return sysActivity;
12302                }
12303                if (sysActivity.info.targetActivity != null) {
12304                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12305                        return sysActivity;
12306                    }
12307                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12308                        return sysActivity;
12309                    }
12310                }
12311            }
12312            return null;
12313        }
12314
12315        public class IterGenerator<E> {
12316            public Iterator<E> generate(ActivityIntentInfo info) {
12317                return null;
12318            }
12319        }
12320
12321        public class ActionIterGenerator extends IterGenerator<String> {
12322            @Override
12323            public Iterator<String> generate(ActivityIntentInfo info) {
12324                return info.actionsIterator();
12325            }
12326        }
12327
12328        public class CategoriesIterGenerator extends IterGenerator<String> {
12329            @Override
12330            public Iterator<String> generate(ActivityIntentInfo info) {
12331                return info.categoriesIterator();
12332            }
12333        }
12334
12335        public class SchemesIterGenerator extends IterGenerator<String> {
12336            @Override
12337            public Iterator<String> generate(ActivityIntentInfo info) {
12338                return info.schemesIterator();
12339            }
12340        }
12341
12342        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12343            @Override
12344            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12345                return info.authoritiesIterator();
12346            }
12347        }
12348
12349        /**
12350         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12351         * MODIFIED. Do not pass in a list that should not be changed.
12352         */
12353        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12354                IterGenerator<T> generator, Iterator<T> searchIterator) {
12355            // loop through the set of actions; every one must be found in the intent filter
12356            while (searchIterator.hasNext()) {
12357                // we must have at least one filter in the list to consider a match
12358                if (intentList.size() == 0) {
12359                    break;
12360                }
12361
12362                final T searchAction = searchIterator.next();
12363
12364                // loop through the set of intent filters
12365                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12366                while (intentIter.hasNext()) {
12367                    final ActivityIntentInfo intentInfo = intentIter.next();
12368                    boolean selectionFound = false;
12369
12370                    // loop through the intent filter's selection criteria; at least one
12371                    // of them must match the searched criteria
12372                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12373                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12374                        final T intentSelection = intentSelectionIter.next();
12375                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12376                            selectionFound = true;
12377                            break;
12378                        }
12379                    }
12380
12381                    // the selection criteria wasn't found in this filter's set; this filter
12382                    // is not a potential match
12383                    if (!selectionFound) {
12384                        intentIter.remove();
12385                    }
12386                }
12387            }
12388        }
12389
12390        private boolean isProtectedAction(ActivityIntentInfo filter) {
12391            final Iterator<String> actionsIter = filter.actionsIterator();
12392            while (actionsIter != null && actionsIter.hasNext()) {
12393                final String filterAction = actionsIter.next();
12394                if (PROTECTED_ACTIONS.contains(filterAction)) {
12395                    return true;
12396                }
12397            }
12398            return false;
12399        }
12400
12401        /**
12402         * Adjusts the priority of the given intent filter according to policy.
12403         * <p>
12404         * <ul>
12405         * <li>The priority for non privileged applications is capped to '0'</li>
12406         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12407         * <li>The priority for unbundled updates to privileged applications is capped to the
12408         *      priority defined on the system partition</li>
12409         * </ul>
12410         * <p>
12411         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12412         * allowed to obtain any priority on any action.
12413         */
12414        private void adjustPriority(
12415                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12416            // nothing to do; priority is fine as-is
12417            if (intent.getPriority() <= 0) {
12418                return;
12419            }
12420
12421            final ActivityInfo activityInfo = intent.activity.info;
12422            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12423
12424            final boolean privilegedApp =
12425                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12426            if (!privilegedApp) {
12427                // non-privileged applications can never define a priority >0
12428                if (DEBUG_FILTERS) {
12429                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12430                            + " package: " + applicationInfo.packageName
12431                            + " activity: " + intent.activity.className
12432                            + " origPrio: " + intent.getPriority());
12433                }
12434                intent.setPriority(0);
12435                return;
12436            }
12437
12438            if (systemActivities == null) {
12439                // the system package is not disabled; we're parsing the system partition
12440                if (isProtectedAction(intent)) {
12441                    if (mDeferProtectedFilters) {
12442                        // We can't deal with these just yet. No component should ever obtain a
12443                        // >0 priority for a protected actions, with ONE exception -- the setup
12444                        // wizard. The setup wizard, however, cannot be known until we're able to
12445                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12446                        // until all intent filters have been processed. Chicken, meet egg.
12447                        // Let the filter temporarily have a high priority and rectify the
12448                        // priorities after all system packages have been scanned.
12449                        mProtectedFilters.add(intent);
12450                        if (DEBUG_FILTERS) {
12451                            Slog.i(TAG, "Protected action; save for later;"
12452                                    + " package: " + applicationInfo.packageName
12453                                    + " activity: " + intent.activity.className
12454                                    + " origPrio: " + intent.getPriority());
12455                        }
12456                        return;
12457                    } else {
12458                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12459                            Slog.i(TAG, "No setup wizard;"
12460                                + " All protected intents capped to priority 0");
12461                        }
12462                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12463                            if (DEBUG_FILTERS) {
12464                                Slog.i(TAG, "Found setup wizard;"
12465                                    + " allow priority " + intent.getPriority() + ";"
12466                                    + " package: " + intent.activity.info.packageName
12467                                    + " activity: " + intent.activity.className
12468                                    + " priority: " + intent.getPriority());
12469                            }
12470                            // setup wizard gets whatever it wants
12471                            return;
12472                        }
12473                        if (DEBUG_FILTERS) {
12474                            Slog.i(TAG, "Protected action; cap priority to 0;"
12475                                    + " package: " + intent.activity.info.packageName
12476                                    + " activity: " + intent.activity.className
12477                                    + " origPrio: " + intent.getPriority());
12478                        }
12479                        intent.setPriority(0);
12480                        return;
12481                    }
12482                }
12483                // privileged apps on the system image get whatever priority they request
12484                return;
12485            }
12486
12487            // privileged app unbundled update ... try to find the same activity
12488            final PackageParser.Activity foundActivity =
12489                    findMatchingActivity(systemActivities, activityInfo);
12490            if (foundActivity == null) {
12491                // this is a new activity; it cannot obtain >0 priority
12492                if (DEBUG_FILTERS) {
12493                    Slog.i(TAG, "New activity; cap priority to 0;"
12494                            + " package: " + applicationInfo.packageName
12495                            + " activity: " + intent.activity.className
12496                            + " origPrio: " + intent.getPriority());
12497                }
12498                intent.setPriority(0);
12499                return;
12500            }
12501
12502            // found activity, now check for filter equivalence
12503
12504            // a shallow copy is enough; we modify the list, not its contents
12505            final List<ActivityIntentInfo> intentListCopy =
12506                    new ArrayList<>(foundActivity.intents);
12507            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12508
12509            // find matching action subsets
12510            final Iterator<String> actionsIterator = intent.actionsIterator();
12511            if (actionsIterator != null) {
12512                getIntentListSubset(
12513                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12514                if (intentListCopy.size() == 0) {
12515                    // no more intents to match; we're not equivalent
12516                    if (DEBUG_FILTERS) {
12517                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12518                                + " package: " + applicationInfo.packageName
12519                                + " activity: " + intent.activity.className
12520                                + " origPrio: " + intent.getPriority());
12521                    }
12522                    intent.setPriority(0);
12523                    return;
12524                }
12525            }
12526
12527            // find matching category subsets
12528            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12529            if (categoriesIterator != null) {
12530                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12531                        categoriesIterator);
12532                if (intentListCopy.size() == 0) {
12533                    // no more intents to match; we're not equivalent
12534                    if (DEBUG_FILTERS) {
12535                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12536                                + " package: " + applicationInfo.packageName
12537                                + " activity: " + intent.activity.className
12538                                + " origPrio: " + intent.getPriority());
12539                    }
12540                    intent.setPriority(0);
12541                    return;
12542                }
12543            }
12544
12545            // find matching schemes subsets
12546            final Iterator<String> schemesIterator = intent.schemesIterator();
12547            if (schemesIterator != null) {
12548                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12549                        schemesIterator);
12550                if (intentListCopy.size() == 0) {
12551                    // no more intents to match; we're not equivalent
12552                    if (DEBUG_FILTERS) {
12553                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12554                                + " package: " + applicationInfo.packageName
12555                                + " activity: " + intent.activity.className
12556                                + " origPrio: " + intent.getPriority());
12557                    }
12558                    intent.setPriority(0);
12559                    return;
12560                }
12561            }
12562
12563            // find matching authorities subsets
12564            final Iterator<IntentFilter.AuthorityEntry>
12565                    authoritiesIterator = intent.authoritiesIterator();
12566            if (authoritiesIterator != null) {
12567                getIntentListSubset(intentListCopy,
12568                        new AuthoritiesIterGenerator(),
12569                        authoritiesIterator);
12570                if (intentListCopy.size() == 0) {
12571                    // no more intents to match; we're not equivalent
12572                    if (DEBUG_FILTERS) {
12573                        Slog.i(TAG, "Mismatched authority; 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            // we found matching filter(s); app gets the max priority of all intents
12584            int cappedPriority = 0;
12585            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12586                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12587            }
12588            if (intent.getPriority() > cappedPriority) {
12589                if (DEBUG_FILTERS) {
12590                    Slog.i(TAG, "Found matching filter(s);"
12591                            + " cap priority to " + cappedPriority + ";"
12592                            + " package: " + applicationInfo.packageName
12593                            + " activity: " + intent.activity.className
12594                            + " origPrio: " + intent.getPriority());
12595                }
12596                intent.setPriority(cappedPriority);
12597                return;
12598            }
12599            // all this for nothing; the requested priority was <= what was on the system
12600        }
12601
12602        public final void addActivity(PackageParser.Activity a, String type) {
12603            mActivities.put(a.getComponentName(), a);
12604            if (DEBUG_SHOW_INFO)
12605                Log.v(
12606                TAG, "  " + type + " " +
12607                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12608            if (DEBUG_SHOW_INFO)
12609                Log.v(TAG, "    Class=" + a.info.name);
12610            final int NI = a.intents.size();
12611            for (int j=0; j<NI; j++) {
12612                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12613                if ("activity".equals(type)) {
12614                    final PackageSetting ps =
12615                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12616                    final List<PackageParser.Activity> systemActivities =
12617                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12618                    adjustPriority(systemActivities, intent);
12619                }
12620                if (DEBUG_SHOW_INFO) {
12621                    Log.v(TAG, "    IntentFilter:");
12622                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12623                }
12624                if (!intent.debugCheck()) {
12625                    Log.w(TAG, "==> For Activity " + a.info.name);
12626                }
12627                addFilter(intent);
12628            }
12629        }
12630
12631        public final void removeActivity(PackageParser.Activity a, String type) {
12632            mActivities.remove(a.getComponentName());
12633            if (DEBUG_SHOW_INFO) {
12634                Log.v(TAG, "  " + type + " "
12635                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12636                                : a.info.name) + ":");
12637                Log.v(TAG, "    Class=" + a.info.name);
12638            }
12639            final int NI = a.intents.size();
12640            for (int j=0; j<NI; j++) {
12641                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12642                if (DEBUG_SHOW_INFO) {
12643                    Log.v(TAG, "    IntentFilter:");
12644                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12645                }
12646                removeFilter(intent);
12647            }
12648        }
12649
12650        @Override
12651        protected boolean allowFilterResult(
12652                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12653            ActivityInfo filterAi = filter.activity.info;
12654            for (int i=dest.size()-1; i>=0; i--) {
12655                ActivityInfo destAi = dest.get(i).activityInfo;
12656                if (destAi.name == filterAi.name
12657                        && destAi.packageName == filterAi.packageName) {
12658                    return false;
12659                }
12660            }
12661            return true;
12662        }
12663
12664        @Override
12665        protected ActivityIntentInfo[] newArray(int size) {
12666            return new ActivityIntentInfo[size];
12667        }
12668
12669        @Override
12670        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12671            if (!sUserManager.exists(userId)) return true;
12672            PackageParser.Package p = filter.activity.owner;
12673            if (p != null) {
12674                PackageSetting ps = (PackageSetting)p.mExtras;
12675                if (ps != null) {
12676                    // System apps are never considered stopped for purposes of
12677                    // filtering, because there may be no way for the user to
12678                    // actually re-launch them.
12679                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12680                            && ps.getStopped(userId);
12681                }
12682            }
12683            return false;
12684        }
12685
12686        @Override
12687        protected boolean isPackageForFilter(String packageName,
12688                PackageParser.ActivityIntentInfo info) {
12689            return packageName.equals(info.activity.owner.packageName);
12690        }
12691
12692        @Override
12693        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12694                int match, int userId) {
12695            if (!sUserManager.exists(userId)) return null;
12696            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12697                return null;
12698            }
12699            final PackageParser.Activity activity = info.activity;
12700            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12701            if (ps == null) {
12702                return null;
12703            }
12704            final PackageUserState userState = ps.readUserState(userId);
12705            ActivityInfo ai =
12706                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12707            if (ai == null) {
12708                return null;
12709            }
12710            final boolean matchExplicitlyVisibleOnly =
12711                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12712            final boolean matchVisibleToInstantApp =
12713                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12714            final boolean componentVisible =
12715                    matchVisibleToInstantApp
12716                    && info.isVisibleToInstantApp()
12717                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12718            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12719            // throw out filters that aren't visible to ephemeral apps
12720            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12721                return null;
12722            }
12723            // throw out instant app filters if we're not explicitly requesting them
12724            if (!matchInstantApp && userState.instantApp) {
12725                return null;
12726            }
12727            // throw out instant app filters if updates are available; will trigger
12728            // instant app resolution
12729            if (userState.instantApp && ps.isUpdateAvailable()) {
12730                return null;
12731            }
12732            final ResolveInfo res = new ResolveInfo();
12733            res.activityInfo = ai;
12734            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12735                res.filter = info;
12736            }
12737            if (info != null) {
12738                res.handleAllWebDataURI = info.handleAllWebDataURI();
12739            }
12740            res.priority = info.getPriority();
12741            res.preferredOrder = activity.owner.mPreferredOrder;
12742            //System.out.println("Result: " + res.activityInfo.className +
12743            //                   " = " + res.priority);
12744            res.match = match;
12745            res.isDefault = info.hasDefault;
12746            res.labelRes = info.labelRes;
12747            res.nonLocalizedLabel = info.nonLocalizedLabel;
12748            if (userNeedsBadging(userId)) {
12749                res.noResourceId = true;
12750            } else {
12751                res.icon = info.icon;
12752            }
12753            res.iconResourceId = info.icon;
12754            res.system = res.activityInfo.applicationInfo.isSystemApp();
12755            res.isInstantAppAvailable = userState.instantApp;
12756            return res;
12757        }
12758
12759        @Override
12760        protected void sortResults(List<ResolveInfo> results) {
12761            Collections.sort(results, mResolvePrioritySorter);
12762        }
12763
12764        @Override
12765        protected void dumpFilter(PrintWriter out, String prefix,
12766                PackageParser.ActivityIntentInfo filter) {
12767            out.print(prefix); out.print(
12768                    Integer.toHexString(System.identityHashCode(filter.activity)));
12769                    out.print(' ');
12770                    filter.activity.printComponentShortName(out);
12771                    out.print(" filter ");
12772                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12773        }
12774
12775        @Override
12776        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12777            return filter.activity;
12778        }
12779
12780        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12781            PackageParser.Activity activity = (PackageParser.Activity)label;
12782            out.print(prefix); out.print(
12783                    Integer.toHexString(System.identityHashCode(activity)));
12784                    out.print(' ');
12785                    activity.printComponentShortName(out);
12786            if (count > 1) {
12787                out.print(" ("); out.print(count); out.print(" filters)");
12788            }
12789            out.println();
12790        }
12791
12792        // Keys are String (activity class name), values are Activity.
12793        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12794                = new ArrayMap<ComponentName, PackageParser.Activity>();
12795        private int mFlags;
12796    }
12797
12798    private final class ServiceIntentResolver
12799            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12800        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12801                boolean defaultOnly, int userId) {
12802            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12803            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12804        }
12805
12806        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12807                int userId) {
12808            if (!sUserManager.exists(userId)) return null;
12809            mFlags = flags;
12810            return super.queryIntent(intent, resolvedType,
12811                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12812                    userId);
12813        }
12814
12815        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12816                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12817            if (!sUserManager.exists(userId)) return null;
12818            if (packageServices == null) {
12819                return null;
12820            }
12821            mFlags = flags;
12822            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12823            final int N = packageServices.size();
12824            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12825                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12826
12827            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12828            for (int i = 0; i < N; ++i) {
12829                intentFilters = packageServices.get(i).intents;
12830                if (intentFilters != null && intentFilters.size() > 0) {
12831                    PackageParser.ServiceIntentInfo[] array =
12832                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12833                    intentFilters.toArray(array);
12834                    listCut.add(array);
12835                }
12836            }
12837            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12838        }
12839
12840        public final void addService(PackageParser.Service s) {
12841            mServices.put(s.getComponentName(), s);
12842            if (DEBUG_SHOW_INFO) {
12843                Log.v(TAG, "  "
12844                        + (s.info.nonLocalizedLabel != null
12845                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12846                Log.v(TAG, "    Class=" + s.info.name);
12847            }
12848            final int NI = s.intents.size();
12849            int j;
12850            for (j=0; j<NI; j++) {
12851                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12852                if (DEBUG_SHOW_INFO) {
12853                    Log.v(TAG, "    IntentFilter:");
12854                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12855                }
12856                if (!intent.debugCheck()) {
12857                    Log.w(TAG, "==> For Service " + s.info.name);
12858                }
12859                addFilter(intent);
12860            }
12861        }
12862
12863        public final void removeService(PackageParser.Service s) {
12864            mServices.remove(s.getComponentName());
12865            if (DEBUG_SHOW_INFO) {
12866                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12867                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12868                Log.v(TAG, "    Class=" + s.info.name);
12869            }
12870            final int NI = s.intents.size();
12871            int j;
12872            for (j=0; j<NI; j++) {
12873                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12874                if (DEBUG_SHOW_INFO) {
12875                    Log.v(TAG, "    IntentFilter:");
12876                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12877                }
12878                removeFilter(intent);
12879            }
12880        }
12881
12882        @Override
12883        protected boolean allowFilterResult(
12884                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12885            ServiceInfo filterSi = filter.service.info;
12886            for (int i=dest.size()-1; i>=0; i--) {
12887                ServiceInfo destAi = dest.get(i).serviceInfo;
12888                if (destAi.name == filterSi.name
12889                        && destAi.packageName == filterSi.packageName) {
12890                    return false;
12891                }
12892            }
12893            return true;
12894        }
12895
12896        @Override
12897        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12898            return new PackageParser.ServiceIntentInfo[size];
12899        }
12900
12901        @Override
12902        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12903            if (!sUserManager.exists(userId)) return true;
12904            PackageParser.Package p = filter.service.owner;
12905            if (p != null) {
12906                PackageSetting ps = (PackageSetting)p.mExtras;
12907                if (ps != null) {
12908                    // System apps are never considered stopped for purposes of
12909                    // filtering, because there may be no way for the user to
12910                    // actually re-launch them.
12911                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12912                            && ps.getStopped(userId);
12913                }
12914            }
12915            return false;
12916        }
12917
12918        @Override
12919        protected boolean isPackageForFilter(String packageName,
12920                PackageParser.ServiceIntentInfo info) {
12921            return packageName.equals(info.service.owner.packageName);
12922        }
12923
12924        @Override
12925        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12926                int match, int userId) {
12927            if (!sUserManager.exists(userId)) return null;
12928            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12929            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12930                return null;
12931            }
12932            final PackageParser.Service service = info.service;
12933            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12934            if (ps == null) {
12935                return null;
12936            }
12937            final PackageUserState userState = ps.readUserState(userId);
12938            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12939                    userState, userId);
12940            if (si == null) {
12941                return null;
12942            }
12943            final boolean matchVisibleToInstantApp =
12944                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12945            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12946            // throw out filters that aren't visible to ephemeral apps
12947            if (matchVisibleToInstantApp
12948                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12949                return null;
12950            }
12951            // throw out ephemeral filters if we're not explicitly requesting them
12952            if (!isInstantApp && userState.instantApp) {
12953                return null;
12954            }
12955            // throw out instant app filters if updates are available; will trigger
12956            // instant app resolution
12957            if (userState.instantApp && ps.isUpdateAvailable()) {
12958                return null;
12959            }
12960            final ResolveInfo res = new ResolveInfo();
12961            res.serviceInfo = si;
12962            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12963                res.filter = filter;
12964            }
12965            res.priority = info.getPriority();
12966            res.preferredOrder = service.owner.mPreferredOrder;
12967            res.match = match;
12968            res.isDefault = info.hasDefault;
12969            res.labelRes = info.labelRes;
12970            res.nonLocalizedLabel = info.nonLocalizedLabel;
12971            res.icon = info.icon;
12972            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12973            return res;
12974        }
12975
12976        @Override
12977        protected void sortResults(List<ResolveInfo> results) {
12978            Collections.sort(results, mResolvePrioritySorter);
12979        }
12980
12981        @Override
12982        protected void dumpFilter(PrintWriter out, String prefix,
12983                PackageParser.ServiceIntentInfo filter) {
12984            out.print(prefix); out.print(
12985                    Integer.toHexString(System.identityHashCode(filter.service)));
12986                    out.print(' ');
12987                    filter.service.printComponentShortName(out);
12988                    out.print(" filter ");
12989                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12990                    if (filter.service.info.permission != null) {
12991                        out.print(" permission "); out.println(filter.service.info.permission);
12992                    } else {
12993                        out.println();
12994                    }
12995        }
12996
12997        @Override
12998        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12999            return filter.service;
13000        }
13001
13002        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13003            PackageParser.Service service = (PackageParser.Service)label;
13004            out.print(prefix); out.print(
13005                    Integer.toHexString(System.identityHashCode(service)));
13006                    out.print(' ');
13007                    service.printComponentShortName(out);
13008            if (count > 1) {
13009                out.print(" ("); out.print(count); out.print(" filters)");
13010            }
13011            out.println();
13012        }
13013
13014//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13015//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13016//            final List<ResolveInfo> retList = Lists.newArrayList();
13017//            while (i.hasNext()) {
13018//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13019//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13020//                    retList.add(resolveInfo);
13021//                }
13022//            }
13023//            return retList;
13024//        }
13025
13026        // Keys are String (activity class name), values are Activity.
13027        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13028                = new ArrayMap<ComponentName, PackageParser.Service>();
13029        private int mFlags;
13030    }
13031
13032    private final class ProviderIntentResolver
13033            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13034        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13035                boolean defaultOnly, int userId) {
13036            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13037            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13038        }
13039
13040        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13041                int userId) {
13042            if (!sUserManager.exists(userId))
13043                return null;
13044            mFlags = flags;
13045            return super.queryIntent(intent, resolvedType,
13046                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13047                    userId);
13048        }
13049
13050        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13051                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13052            if (!sUserManager.exists(userId))
13053                return null;
13054            if (packageProviders == null) {
13055                return null;
13056            }
13057            mFlags = flags;
13058            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13059            final int N = packageProviders.size();
13060            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13061                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13062
13063            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13064            for (int i = 0; i < N; ++i) {
13065                intentFilters = packageProviders.get(i).intents;
13066                if (intentFilters != null && intentFilters.size() > 0) {
13067                    PackageParser.ProviderIntentInfo[] array =
13068                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13069                    intentFilters.toArray(array);
13070                    listCut.add(array);
13071                }
13072            }
13073            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13074        }
13075
13076        public final void addProvider(PackageParser.Provider p) {
13077            if (mProviders.containsKey(p.getComponentName())) {
13078                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13079                return;
13080            }
13081
13082            mProviders.put(p.getComponentName(), p);
13083            if (DEBUG_SHOW_INFO) {
13084                Log.v(TAG, "  "
13085                        + (p.info.nonLocalizedLabel != null
13086                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13087                Log.v(TAG, "    Class=" + p.info.name);
13088            }
13089            final int NI = p.intents.size();
13090            int j;
13091            for (j = 0; j < NI; j++) {
13092                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13093                if (DEBUG_SHOW_INFO) {
13094                    Log.v(TAG, "    IntentFilter:");
13095                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13096                }
13097                if (!intent.debugCheck()) {
13098                    Log.w(TAG, "==> For Provider " + p.info.name);
13099                }
13100                addFilter(intent);
13101            }
13102        }
13103
13104        public final void removeProvider(PackageParser.Provider p) {
13105            mProviders.remove(p.getComponentName());
13106            if (DEBUG_SHOW_INFO) {
13107                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13108                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13109                Log.v(TAG, "    Class=" + p.info.name);
13110            }
13111            final int NI = p.intents.size();
13112            int j;
13113            for (j = 0; j < NI; j++) {
13114                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13115                if (DEBUG_SHOW_INFO) {
13116                    Log.v(TAG, "    IntentFilter:");
13117                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13118                }
13119                removeFilter(intent);
13120            }
13121        }
13122
13123        @Override
13124        protected boolean allowFilterResult(
13125                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13126            ProviderInfo filterPi = filter.provider.info;
13127            for (int i = dest.size() - 1; i >= 0; i--) {
13128                ProviderInfo destPi = dest.get(i).providerInfo;
13129                if (destPi.name == filterPi.name
13130                        && destPi.packageName == filterPi.packageName) {
13131                    return false;
13132                }
13133            }
13134            return true;
13135        }
13136
13137        @Override
13138        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13139            return new PackageParser.ProviderIntentInfo[size];
13140        }
13141
13142        @Override
13143        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13144            if (!sUserManager.exists(userId))
13145                return true;
13146            PackageParser.Package p = filter.provider.owner;
13147            if (p != null) {
13148                PackageSetting ps = (PackageSetting) p.mExtras;
13149                if (ps != null) {
13150                    // System apps are never considered stopped for purposes of
13151                    // filtering, because there may be no way for the user to
13152                    // actually re-launch them.
13153                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13154                            && ps.getStopped(userId);
13155                }
13156            }
13157            return false;
13158        }
13159
13160        @Override
13161        protected boolean isPackageForFilter(String packageName,
13162                PackageParser.ProviderIntentInfo info) {
13163            return packageName.equals(info.provider.owner.packageName);
13164        }
13165
13166        @Override
13167        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13168                int match, int userId) {
13169            if (!sUserManager.exists(userId))
13170                return null;
13171            final PackageParser.ProviderIntentInfo info = filter;
13172            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13173                return null;
13174            }
13175            final PackageParser.Provider provider = info.provider;
13176            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13177            if (ps == null) {
13178                return null;
13179            }
13180            final PackageUserState userState = ps.readUserState(userId);
13181            final boolean matchVisibleToInstantApp =
13182                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13183            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13184            // throw out filters that aren't visible to instant applications
13185            if (matchVisibleToInstantApp
13186                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13187                return null;
13188            }
13189            // throw out instant application filters if we're not explicitly requesting them
13190            if (!isInstantApp && userState.instantApp) {
13191                return null;
13192            }
13193            // throw out instant application filters if updates are available; will trigger
13194            // instant application resolution
13195            if (userState.instantApp && ps.isUpdateAvailable()) {
13196                return null;
13197            }
13198            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13199                    userState, userId);
13200            if (pi == null) {
13201                return null;
13202            }
13203            final ResolveInfo res = new ResolveInfo();
13204            res.providerInfo = pi;
13205            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13206                res.filter = filter;
13207            }
13208            res.priority = info.getPriority();
13209            res.preferredOrder = provider.owner.mPreferredOrder;
13210            res.match = match;
13211            res.isDefault = info.hasDefault;
13212            res.labelRes = info.labelRes;
13213            res.nonLocalizedLabel = info.nonLocalizedLabel;
13214            res.icon = info.icon;
13215            res.system = res.providerInfo.applicationInfo.isSystemApp();
13216            return res;
13217        }
13218
13219        @Override
13220        protected void sortResults(List<ResolveInfo> results) {
13221            Collections.sort(results, mResolvePrioritySorter);
13222        }
13223
13224        @Override
13225        protected void dumpFilter(PrintWriter out, String prefix,
13226                PackageParser.ProviderIntentInfo filter) {
13227            out.print(prefix);
13228            out.print(
13229                    Integer.toHexString(System.identityHashCode(filter.provider)));
13230            out.print(' ');
13231            filter.provider.printComponentShortName(out);
13232            out.print(" filter ");
13233            out.println(Integer.toHexString(System.identityHashCode(filter)));
13234        }
13235
13236        @Override
13237        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13238            return filter.provider;
13239        }
13240
13241        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13242            PackageParser.Provider provider = (PackageParser.Provider)label;
13243            out.print(prefix); out.print(
13244                    Integer.toHexString(System.identityHashCode(provider)));
13245                    out.print(' ');
13246                    provider.printComponentShortName(out);
13247            if (count > 1) {
13248                out.print(" ("); out.print(count); out.print(" filters)");
13249            }
13250            out.println();
13251        }
13252
13253        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13254                = new ArrayMap<ComponentName, PackageParser.Provider>();
13255        private int mFlags;
13256    }
13257
13258    static final class InstantAppIntentResolver
13259            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13260            AuxiliaryResolveInfo.AuxiliaryFilter> {
13261        /**
13262         * The result that has the highest defined order. Ordering applies on a
13263         * per-package basis. Mapping is from package name to Pair of order and
13264         * EphemeralResolveInfo.
13265         * <p>
13266         * NOTE: This is implemented as a field variable for convenience and efficiency.
13267         * By having a field variable, we're able to track filter ordering as soon as
13268         * a non-zero order is defined. Otherwise, multiple loops across the result set
13269         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13270         * this needs to be contained entirely within {@link #filterResults}.
13271         */
13272        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13273
13274        @Override
13275        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13276            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13277        }
13278
13279        @Override
13280        protected boolean isPackageForFilter(String packageName,
13281                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13282            return true;
13283        }
13284
13285        @Override
13286        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13287                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13288            if (!sUserManager.exists(userId)) {
13289                return null;
13290            }
13291            final String packageName = responseObj.resolveInfo.getPackageName();
13292            final Integer order = responseObj.getOrder();
13293            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13294                    mOrderResult.get(packageName);
13295            // ordering is enabled and this item's order isn't high enough
13296            if (lastOrderResult != null && lastOrderResult.first >= order) {
13297                return null;
13298            }
13299            final InstantAppResolveInfo res = responseObj.resolveInfo;
13300            if (order > 0) {
13301                // non-zero order, enable ordering
13302                mOrderResult.put(packageName, new Pair<>(order, res));
13303            }
13304            return responseObj;
13305        }
13306
13307        @Override
13308        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13309            // only do work if ordering is enabled [most of the time it won't be]
13310            if (mOrderResult.size() == 0) {
13311                return;
13312            }
13313            int resultSize = results.size();
13314            for (int i = 0; i < resultSize; i++) {
13315                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13316                final String packageName = info.getPackageName();
13317                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13318                if (savedInfo == null) {
13319                    // package doesn't having ordering
13320                    continue;
13321                }
13322                if (savedInfo.second == info) {
13323                    // circled back to the highest ordered item; remove from order list
13324                    mOrderResult.remove(packageName);
13325                    if (mOrderResult.size() == 0) {
13326                        // no more ordered items
13327                        break;
13328                    }
13329                    continue;
13330                }
13331                // item has a worse order, remove it from the result list
13332                results.remove(i);
13333                resultSize--;
13334                i--;
13335            }
13336        }
13337    }
13338
13339    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13340            new Comparator<ResolveInfo>() {
13341        public int compare(ResolveInfo r1, ResolveInfo r2) {
13342            int v1 = r1.priority;
13343            int v2 = r2.priority;
13344            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13345            if (v1 != v2) {
13346                return (v1 > v2) ? -1 : 1;
13347            }
13348            v1 = r1.preferredOrder;
13349            v2 = r2.preferredOrder;
13350            if (v1 != v2) {
13351                return (v1 > v2) ? -1 : 1;
13352            }
13353            if (r1.isDefault != r2.isDefault) {
13354                return r1.isDefault ? -1 : 1;
13355            }
13356            v1 = r1.match;
13357            v2 = r2.match;
13358            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13359            if (v1 != v2) {
13360                return (v1 > v2) ? -1 : 1;
13361            }
13362            if (r1.system != r2.system) {
13363                return r1.system ? -1 : 1;
13364            }
13365            if (r1.activityInfo != null) {
13366                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13367            }
13368            if (r1.serviceInfo != null) {
13369                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13370            }
13371            if (r1.providerInfo != null) {
13372                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13373            }
13374            return 0;
13375        }
13376    };
13377
13378    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13379            new Comparator<ProviderInfo>() {
13380        public int compare(ProviderInfo p1, ProviderInfo p2) {
13381            final int v1 = p1.initOrder;
13382            final int v2 = p2.initOrder;
13383            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13384        }
13385    };
13386
13387    @Override
13388    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13389            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13390            final int[] userIds, int[] instantUserIds) {
13391        mHandler.post(new Runnable() {
13392            @Override
13393            public void run() {
13394                try {
13395                    final IActivityManager am = ActivityManager.getService();
13396                    if (am == null) return;
13397                    final int[] resolvedUserIds;
13398                    if (userIds == null) {
13399                        resolvedUserIds = am.getRunningUserIds();
13400                    } else {
13401                        resolvedUserIds = userIds;
13402                    }
13403                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13404                            resolvedUserIds, false);
13405                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13406                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13407                                instantUserIds, true);
13408                    }
13409                } catch (RemoteException ex) {
13410                }
13411            }
13412        });
13413    }
13414
13415    @Override
13416    public void notifyPackageAdded(String packageName) {
13417        final PackageListObserver[] observers;
13418        synchronized (mPackages) {
13419            if (mPackageListObservers.size() == 0) {
13420                return;
13421            }
13422            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13423        }
13424        for (int i = observers.length - 1; i >= 0; --i) {
13425            observers[i].onPackageAdded(packageName);
13426        }
13427    }
13428
13429    @Override
13430    public void notifyPackageRemoved(String packageName) {
13431        final PackageListObserver[] observers;
13432        synchronized (mPackages) {
13433            if (mPackageListObservers.size() == 0) {
13434                return;
13435            }
13436            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13437        }
13438        for (int i = observers.length - 1; i >= 0; --i) {
13439            observers[i].onPackageRemoved(packageName);
13440        }
13441    }
13442
13443    /**
13444     * Sends a broadcast for the given action.
13445     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13446     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13447     * the system and applications allowed to see instant applications to receive package
13448     * lifecycle events for instant applications.
13449     */
13450    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13451            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13452            int[] userIds, boolean isInstantApp)
13453                    throws RemoteException {
13454        for (int id : userIds) {
13455            final Intent intent = new Intent(action,
13456                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13457            final String[] requiredPermissions =
13458                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13459            if (extras != null) {
13460                intent.putExtras(extras);
13461            }
13462            if (targetPkg != null) {
13463                intent.setPackage(targetPkg);
13464            }
13465            // Modify the UID when posting to other users
13466            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13467            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13468                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13469                intent.putExtra(Intent.EXTRA_UID, uid);
13470            }
13471            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13472            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13473            if (DEBUG_BROADCASTS) {
13474                RuntimeException here = new RuntimeException("here");
13475                here.fillInStackTrace();
13476                Slog.d(TAG, "Sending to user " + id + ": "
13477                        + intent.toShortString(false, true, false, false)
13478                        + " " + intent.getExtras(), here);
13479            }
13480            am.broadcastIntent(null, intent, null, finishedReceiver,
13481                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13482                    null, finishedReceiver != null, false, id);
13483        }
13484    }
13485
13486    /**
13487     * Check if the external storage media is available. This is true if there
13488     * is a mounted external storage medium or if the external storage is
13489     * emulated.
13490     */
13491    private boolean isExternalMediaAvailable() {
13492        return mMediaMounted || Environment.isExternalStorageEmulated();
13493    }
13494
13495    @Override
13496    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13497        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13498            return null;
13499        }
13500        if (!isExternalMediaAvailable()) {
13501                // If the external storage is no longer mounted at this point,
13502                // the caller may not have been able to delete all of this
13503                // packages files and can not delete any more.  Bail.
13504            return null;
13505        }
13506        synchronized (mPackages) {
13507            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13508            if (lastPackage != null) {
13509                pkgs.remove(lastPackage);
13510            }
13511            if (pkgs.size() > 0) {
13512                return pkgs.get(0);
13513            }
13514        }
13515        return null;
13516    }
13517
13518    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13519        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13520                userId, andCode ? 1 : 0, packageName);
13521        if (mSystemReady) {
13522            msg.sendToTarget();
13523        } else {
13524            if (mPostSystemReadyMessages == null) {
13525                mPostSystemReadyMessages = new ArrayList<>();
13526            }
13527            mPostSystemReadyMessages.add(msg);
13528        }
13529    }
13530
13531    void startCleaningPackages() {
13532        // reader
13533        if (!isExternalMediaAvailable()) {
13534            return;
13535        }
13536        synchronized (mPackages) {
13537            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13538                return;
13539            }
13540        }
13541        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13542        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13543        IActivityManager am = ActivityManager.getService();
13544        if (am != null) {
13545            int dcsUid = -1;
13546            synchronized (mPackages) {
13547                if (!mDefaultContainerWhitelisted) {
13548                    mDefaultContainerWhitelisted = true;
13549                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13550                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13551                }
13552            }
13553            try {
13554                if (dcsUid > 0) {
13555                    am.backgroundWhitelistUid(dcsUid);
13556                }
13557                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13558                        UserHandle.USER_SYSTEM);
13559            } catch (RemoteException e) {
13560            }
13561        }
13562    }
13563
13564    /**
13565     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13566     * it is acting on behalf on an enterprise or the user).
13567     *
13568     * Note that the ordering of the conditionals in this method is important. The checks we perform
13569     * are as follows, in this order:
13570     *
13571     * 1) If the install is being performed by a system app, we can trust the app to have set the
13572     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13573     *    what it is.
13574     * 2) If the install is being performed by a device or profile owner app, the install reason
13575     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13576     *    set the install reason correctly. If the app targets an older SDK version where install
13577     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13578     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13579     * 3) In all other cases, the install is being performed by a regular app that is neither part
13580     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13581     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13582     *    set to enterprise policy and if so, change it to unknown instead.
13583     */
13584    private int fixUpInstallReason(String installerPackageName, int installerUid,
13585            int installReason) {
13586        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13587                == PERMISSION_GRANTED) {
13588            // If the install is being performed by a system app, we trust that app to have set the
13589            // install reason correctly.
13590            return installReason;
13591        }
13592
13593        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13594            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13595        if (dpm != null) {
13596            ComponentName owner = null;
13597            try {
13598                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13599                if (owner == null) {
13600                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13601                }
13602            } catch (RemoteException e) {
13603            }
13604            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13605                // If the install is being performed by a device or profile owner, the install
13606                // reason should be enterprise policy.
13607                return PackageManager.INSTALL_REASON_POLICY;
13608            }
13609        }
13610
13611        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13612            // If the install is being performed by a regular app (i.e. neither system app nor
13613            // device or profile owner), we have no reason to believe that the app is acting on
13614            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13615            // change it to unknown instead.
13616            return PackageManager.INSTALL_REASON_UNKNOWN;
13617        }
13618
13619        // If the install is being performed by a regular app and the install reason was set to any
13620        // value but enterprise policy, leave the install reason unchanged.
13621        return installReason;
13622    }
13623
13624    void installStage(String packageName, File stagedDir,
13625            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13626            String installerPackageName, int installerUid, UserHandle user,
13627            PackageParser.SigningDetails signingDetails) {
13628        if (DEBUG_INSTANT) {
13629            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13630                Slog.d(TAG, "Ephemeral install of " + packageName);
13631            }
13632        }
13633        final VerificationInfo verificationInfo = new VerificationInfo(
13634                sessionParams.originatingUri, sessionParams.referrerUri,
13635                sessionParams.originatingUid, installerUid);
13636
13637        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13638
13639        final Message msg = mHandler.obtainMessage(INIT_COPY);
13640        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13641                sessionParams.installReason);
13642        final InstallParams params = new InstallParams(origin, null, observer,
13643                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13644                verificationInfo, user, sessionParams.abiOverride,
13645                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13646        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13647        msg.obj = params;
13648
13649        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13650                System.identityHashCode(msg.obj));
13651        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13652                System.identityHashCode(msg.obj));
13653
13654        mHandler.sendMessage(msg);
13655    }
13656
13657    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13658            int userId) {
13659        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13660        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13661        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13662        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13663        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13664                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13665
13666        // Send a session commit broadcast
13667        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13668        info.installReason = pkgSetting.getInstallReason(userId);
13669        info.appPackageName = packageName;
13670        sendSessionCommitBroadcast(info, userId);
13671    }
13672
13673    @Override
13674    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13675            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13676        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13677            return;
13678        }
13679        Bundle extras = new Bundle(1);
13680        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13681        final int uid = UserHandle.getUid(
13682                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13683        extras.putInt(Intent.EXTRA_UID, uid);
13684
13685        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13686                packageName, extras, 0, null, null, userIds, instantUserIds);
13687        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13688            mHandler.post(() -> {
13689                        for (int userId : userIds) {
13690                            sendBootCompletedBroadcastToSystemApp(
13691                                    packageName, includeStopped, userId);
13692                        }
13693                    }
13694            );
13695        }
13696    }
13697
13698    /**
13699     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13700     * automatically without needing an explicit launch.
13701     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13702     */
13703    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13704            int userId) {
13705        // If user is not running, the app didn't miss any broadcast
13706        if (!mUserManagerInternal.isUserRunning(userId)) {
13707            return;
13708        }
13709        final IActivityManager am = ActivityManager.getService();
13710        try {
13711            // Deliver LOCKED_BOOT_COMPLETED first
13712            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13713                    .setPackage(packageName);
13714            if (includeStopped) {
13715                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13716            }
13717            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13718            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13719                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13720
13721            // Deliver BOOT_COMPLETED only if user is unlocked
13722            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13723                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13724                if (includeStopped) {
13725                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13726                }
13727                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13728                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13729            }
13730        } catch (RemoteException e) {
13731            throw e.rethrowFromSystemServer();
13732        }
13733    }
13734
13735    @Override
13736    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13737            int userId) {
13738        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13739        PackageSetting pkgSetting;
13740        final int callingUid = Binder.getCallingUid();
13741        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13742                true /* requireFullPermission */, true /* checkShell */,
13743                "setApplicationHiddenSetting for user " + userId);
13744
13745        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13746            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13747            return false;
13748        }
13749
13750        long callingId = Binder.clearCallingIdentity();
13751        try {
13752            boolean sendAdded = false;
13753            boolean sendRemoved = false;
13754            // writer
13755            synchronized (mPackages) {
13756                pkgSetting = mSettings.mPackages.get(packageName);
13757                if (pkgSetting == null) {
13758                    return false;
13759                }
13760                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13761                    return false;
13762                }
13763                // Do not allow "android" is being disabled
13764                if ("android".equals(packageName)) {
13765                    Slog.w(TAG, "Cannot hide package: android");
13766                    return false;
13767                }
13768                // Cannot hide static shared libs as they are considered
13769                // a part of the using app (emulating static linking). Also
13770                // static libs are installed always on internal storage.
13771                PackageParser.Package pkg = mPackages.get(packageName);
13772                if (pkg != null && pkg.staticSharedLibName != null) {
13773                    Slog.w(TAG, "Cannot hide package: " + packageName
13774                            + " providing static shared library: "
13775                            + pkg.staticSharedLibName);
13776                    return false;
13777                }
13778                // Only allow protected packages to hide themselves.
13779                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13780                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13781                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13782                    return false;
13783                }
13784
13785                if (pkgSetting.getHidden(userId) != hidden) {
13786                    pkgSetting.setHidden(hidden, userId);
13787                    mSettings.writePackageRestrictionsLPr(userId);
13788                    if (hidden) {
13789                        sendRemoved = true;
13790                    } else {
13791                        sendAdded = true;
13792                    }
13793                }
13794            }
13795            if (sendAdded) {
13796                sendPackageAddedForUser(packageName, pkgSetting, userId);
13797                return true;
13798            }
13799            if (sendRemoved) {
13800                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13801                        "hiding pkg");
13802                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13803                return true;
13804            }
13805        } finally {
13806            Binder.restoreCallingIdentity(callingId);
13807        }
13808        return false;
13809    }
13810
13811    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13812            int userId) {
13813        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13814        info.removedPackage = packageName;
13815        info.installerPackageName = pkgSetting.installerPackageName;
13816        info.removedUsers = new int[] {userId};
13817        info.broadcastUsers = new int[] {userId};
13818        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13819        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13820    }
13821
13822    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended,
13823            PersistableBundle launcherExtras) {
13824        if (pkgList.length > 0) {
13825            Bundle extras = new Bundle(1);
13826            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13827            if (launcherExtras != null) {
13828                extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13829                        new Bundle(launcherExtras.deepCopy()));
13830            }
13831            sendPackageBroadcast(
13832                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13833                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13834                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13835                    new int[] {userId}, null);
13836        }
13837    }
13838
13839    /**
13840     * Returns true if application is not found or there was an error. Otherwise it returns
13841     * the hidden state of the package for the given user.
13842     */
13843    @Override
13844    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13845        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13846        final int callingUid = Binder.getCallingUid();
13847        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13848                true /* requireFullPermission */, false /* checkShell */,
13849                "getApplicationHidden for user " + userId);
13850        PackageSetting ps;
13851        long callingId = Binder.clearCallingIdentity();
13852        try {
13853            // writer
13854            synchronized (mPackages) {
13855                ps = mSettings.mPackages.get(packageName);
13856                if (ps == null) {
13857                    return true;
13858                }
13859                if (filterAppAccessLPr(ps, callingUid, userId)) {
13860                    return true;
13861                }
13862                return ps.getHidden(userId);
13863            }
13864        } finally {
13865            Binder.restoreCallingIdentity(callingId);
13866        }
13867    }
13868
13869    /**
13870     * @hide
13871     */
13872    @Override
13873    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13874            int installReason) {
13875        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13876                null);
13877        PackageSetting pkgSetting;
13878        final int callingUid = Binder.getCallingUid();
13879        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13880                true /* requireFullPermission */, true /* checkShell */,
13881                "installExistingPackage for user " + userId);
13882        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13883            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13884        }
13885
13886        long callingId = Binder.clearCallingIdentity();
13887        try {
13888            boolean installed = false;
13889            final boolean instantApp =
13890                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13891            final boolean fullApp =
13892                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13893
13894            // writer
13895            synchronized (mPackages) {
13896                pkgSetting = mSettings.mPackages.get(packageName);
13897                if (pkgSetting == null) {
13898                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13899                }
13900                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13901                    // only allow the existing package to be used if it's installed as a full
13902                    // application for at least one user
13903                    boolean installAllowed = false;
13904                    for (int checkUserId : sUserManager.getUserIds()) {
13905                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13906                        if (installAllowed) {
13907                            break;
13908                        }
13909                    }
13910                    if (!installAllowed) {
13911                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13912                    }
13913                }
13914                if (!pkgSetting.getInstalled(userId)) {
13915                    pkgSetting.setInstalled(true, userId);
13916                    pkgSetting.setHidden(false, userId);
13917                    pkgSetting.setInstallReason(installReason, userId);
13918                    mSettings.writePackageRestrictionsLPr(userId);
13919                    mSettings.writeKernelMappingLPr(pkgSetting);
13920                    installed = true;
13921                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13922                    // upgrade app from instant to full; we don't allow app downgrade
13923                    installed = true;
13924                }
13925                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13926            }
13927
13928            if (installed) {
13929                if (pkgSetting.pkg != null) {
13930                    synchronized (mInstallLock) {
13931                        // We don't need to freeze for a brand new install
13932                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13933                    }
13934                }
13935                sendPackageAddedForUser(packageName, pkgSetting, userId);
13936                synchronized (mPackages) {
13937                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13938                }
13939            }
13940        } finally {
13941            Binder.restoreCallingIdentity(callingId);
13942        }
13943
13944        return PackageManager.INSTALL_SUCCEEDED;
13945    }
13946
13947    static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13948            boolean instantApp, boolean fullApp) {
13949        // no state specified; do nothing
13950        if (!instantApp && !fullApp) {
13951            return;
13952        }
13953        if (userId != UserHandle.USER_ALL) {
13954            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13955                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13956            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13957                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13958            }
13959        } else {
13960            for (int currentUserId : sUserManager.getUserIds()) {
13961                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13962                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13963                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13964                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13965                }
13966            }
13967        }
13968    }
13969
13970    boolean isUserRestricted(int userId, String restrictionKey) {
13971        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13972        if (restrictions.getBoolean(restrictionKey, false)) {
13973            Log.w(TAG, "User is restricted: " + restrictionKey);
13974            return true;
13975        }
13976        return false;
13977    }
13978
13979    @Override
13980    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13981            PersistableBundle appExtras, PersistableBundle launcherExtras, String callingPackage,
13982            int userId) {
13983        try {
13984            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
13985        } catch (SecurityException e) {
13986            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
13987                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
13988                            + Manifest.permission.MANAGE_USERS);
13989        }
13990        final int callingUid = Binder.getCallingUid();
13991        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13992                true /* requireFullPermission */, true /* checkShell */,
13993                "setPackagesSuspended for user " + userId);
13994        if (callingUid != Process.ROOT_UID &&
13995                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
13996            throw new IllegalArgumentException("callingPackage " + callingPackage + " does not"
13997                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
13998        }
13999
14000        if (ArrayUtils.isEmpty(packageNames)) {
14001            return packageNames;
14002        }
14003
14004        final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
14005        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14006        final long callingId = Binder.clearCallingIdentity();
14007        try {
14008            synchronized (mPackages) {
14009                for (int i = 0; i < packageNames.length; i++) {
14010                    final String packageName = packageNames[i];
14011                    if (callingPackage.equals(packageName)) {
14012                        Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
14013                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
14014                        unactionedPackages.add(packageName);
14015                        continue;
14016                    }
14017                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14018                    if (pkgSetting == null
14019                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14020                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14021                                + "\". Skipping suspending/un-suspending.");
14022                        unactionedPackages.add(packageName);
14023                        continue;
14024                    }
14025                    if (pkgSetting.getSuspended(userId) != suspended) {
14026                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14027                            unactionedPackages.add(packageName);
14028                            continue;
14029                        }
14030                        pkgSetting.setSuspended(suspended, callingPackage, appExtras,
14031                                launcherExtras, userId);
14032                        changedPackagesList.add(packageName);
14033                    }
14034                }
14035            }
14036        } finally {
14037            Binder.restoreCallingIdentity(callingId);
14038        }
14039        if (!changedPackagesList.isEmpty()) {
14040            final String[] changedPackages = changedPackagesList.toArray(
14041                    new String[changedPackagesList.size()]);
14042            sendPackagesSuspendedForUser(changedPackages, userId, suspended, launcherExtras);
14043            sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
14044            synchronized (mPackages) {
14045                scheduleWritePackageRestrictionsLocked(userId);
14046            }
14047        }
14048
14049        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14050    }
14051
14052    @Override
14053    public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
14054        final int callingUid = Binder.getCallingUid();
14055        if (getPackageUid(packageName, 0, userId) != callingUid) {
14056            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14057        }
14058        synchronized (mPackages) {
14059            final PackageSetting ps = mSettings.mPackages.get(packageName);
14060            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14061                throw new IllegalArgumentException("Unknown target package: " + packageName);
14062            }
14063            final PackageUserState packageUserState = ps.readUserState(userId);
14064            if (packageUserState.suspended) {
14065                return packageUserState.suspendedAppExtras;
14066            }
14067            return null;
14068        }
14069    }
14070
14071    @Override
14072    public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras,
14073            int userId) {
14074        final int callingUid = Binder.getCallingUid();
14075        mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14076        synchronized (mPackages) {
14077            final PackageSetting ps = mSettings.mPackages.get(packageName);
14078            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14079                throw new IllegalArgumentException("Unknown target package: " + packageName);
14080            }
14081            final PackageUserState packageUserState = ps.readUserState(userId);
14082            if (packageUserState.suspended) {
14083                packageUserState.suspendedAppExtras = appExtras;
14084                sendMyPackageSuspendedOrUnsuspended(new String[] {packageName}, true, appExtras,
14085                        userId);
14086            }
14087        }
14088    }
14089
14090    private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
14091            PersistableBundle appExtras, int userId) {
14092        final String action;
14093        final Bundle intentExtras = new Bundle();
14094        if (suspended) {
14095            action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
14096            if (appExtras != null) {
14097                final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
14098                intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
14099            }
14100        } else {
14101            action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
14102        }
14103        mHandler.post(new Runnable() {
14104            @Override
14105            public void run() {
14106                try {
14107                    final IActivityManager am = ActivityManager.getService();
14108                    if (am == null) {
14109                        Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
14110                                + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
14111                        return;
14112                    }
14113                    final int[] targetUserIds = new int[] {userId};
14114                    for (String packageName : affectedPackages) {
14115                        doSendBroadcast(am, action, null, intentExtras,
14116                                Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
14117                                targetUserIds, false);
14118                    }
14119                } catch (RemoteException ex) {
14120                    // Shouldn't happen as AMS is in the same process.
14121                }
14122            }
14123        });
14124    }
14125
14126    @Override
14127    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14128        final int callingUid = Binder.getCallingUid();
14129        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14130                true /* requireFullPermission */, false /* checkShell */,
14131                "isPackageSuspendedForUser for user " + userId);
14132        if (getPackageUid(packageName, 0, userId) != callingUid) {
14133            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14134        }
14135        synchronized (mPackages) {
14136            final PackageSetting ps = mSettings.mPackages.get(packageName);
14137            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14138                throw new IllegalArgumentException("Unknown target package: " + packageName);
14139            }
14140            return ps.getSuspended(userId);
14141        }
14142    }
14143
14144    void onSuspendingPackageRemoved(String packageName, int userId) {
14145        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14146                : new int[] {userId};
14147        synchronized (mPackages) {
14148            for (PackageSetting ps : mSettings.mPackages.values()) {
14149                for (int user : userIds) {
14150                    final PackageUserState pus = ps.readUserState(user);
14151                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14152                        ps.setSuspended(false, null, null, null, user);
14153                    }
14154                }
14155            }
14156        }
14157    }
14158
14159    @GuardedBy("mPackages")
14160    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14161        if (isPackageDeviceAdmin(packageName, userId)) {
14162            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14163                    + "\": has an active device admin");
14164            return false;
14165        }
14166
14167        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14168        if (packageName.equals(activeLauncherPackageName)) {
14169            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14170                    + "\": contains the active launcher");
14171            return false;
14172        }
14173
14174        if (packageName.equals(mRequiredInstallerPackage)) {
14175            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14176                    + "\": required for package installation");
14177            return false;
14178        }
14179
14180        if (packageName.equals(mRequiredUninstallerPackage)) {
14181            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14182                    + "\": required for package uninstallation");
14183            return false;
14184        }
14185
14186        if (packageName.equals(mRequiredVerifierPackage)) {
14187            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14188                    + "\": required for package verification");
14189            return false;
14190        }
14191
14192        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14193            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14194                    + "\": is the default dialer");
14195            return false;
14196        }
14197
14198        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14199            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14200                    + "\": protected package");
14201            return false;
14202        }
14203
14204        // Cannot suspend static shared libs as they are considered
14205        // a part of the using app (emulating static linking). Also
14206        // static libs are installed always on internal storage.
14207        PackageParser.Package pkg = mPackages.get(packageName);
14208        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14209            Slog.w(TAG, "Cannot suspend package: " + packageName
14210                    + " providing static shared library: "
14211                    + pkg.staticSharedLibName);
14212            return false;
14213        }
14214
14215        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14216            Slog.w(TAG, "Cannot suspend package: " + packageName);
14217            return false;
14218        }
14219
14220        return true;
14221    }
14222
14223    private String getActiveLauncherPackageName(int userId) {
14224        Intent intent = new Intent(Intent.ACTION_MAIN);
14225        intent.addCategory(Intent.CATEGORY_HOME);
14226        ResolveInfo resolveInfo = resolveIntent(
14227                intent,
14228                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14229                PackageManager.MATCH_DEFAULT_ONLY,
14230                userId);
14231
14232        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14233    }
14234
14235    private String getDefaultDialerPackageName(int userId) {
14236        synchronized (mPackages) {
14237            return mSettings.getDefaultDialerPackageNameLPw(userId);
14238        }
14239    }
14240
14241    @Override
14242    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14243        mContext.enforceCallingOrSelfPermission(
14244                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14245                "Only package verification agents can verify applications");
14246
14247        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14248        final PackageVerificationResponse response = new PackageVerificationResponse(
14249                verificationCode, Binder.getCallingUid());
14250        msg.arg1 = id;
14251        msg.obj = response;
14252        mHandler.sendMessage(msg);
14253    }
14254
14255    @Override
14256    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14257            long millisecondsToDelay) {
14258        mContext.enforceCallingOrSelfPermission(
14259                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14260                "Only package verification agents can extend verification timeouts");
14261
14262        final PackageVerificationState state = mPendingVerification.get(id);
14263        final PackageVerificationResponse response = new PackageVerificationResponse(
14264                verificationCodeAtTimeout, Binder.getCallingUid());
14265
14266        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14267            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14268        }
14269        if (millisecondsToDelay < 0) {
14270            millisecondsToDelay = 0;
14271        }
14272        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14273                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14274            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14275        }
14276
14277        if ((state != null) && !state.timeoutExtended()) {
14278            state.extendTimeout();
14279
14280            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14281            msg.arg1 = id;
14282            msg.obj = response;
14283            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14284        }
14285    }
14286
14287    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14288            int verificationCode, UserHandle user) {
14289        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14290        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14291        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14292        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14293        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14294
14295        mContext.sendBroadcastAsUser(intent, user,
14296                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14297    }
14298
14299    private ComponentName matchComponentForVerifier(String packageName,
14300            List<ResolveInfo> receivers) {
14301        ActivityInfo targetReceiver = null;
14302
14303        final int NR = receivers.size();
14304        for (int i = 0; i < NR; i++) {
14305            final ResolveInfo info = receivers.get(i);
14306            if (info.activityInfo == null) {
14307                continue;
14308            }
14309
14310            if (packageName.equals(info.activityInfo.packageName)) {
14311                targetReceiver = info.activityInfo;
14312                break;
14313            }
14314        }
14315
14316        if (targetReceiver == null) {
14317            return null;
14318        }
14319
14320        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14321    }
14322
14323    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14324            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14325        if (pkgInfo.verifiers.length == 0) {
14326            return null;
14327        }
14328
14329        final int N = pkgInfo.verifiers.length;
14330        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14331        for (int i = 0; i < N; i++) {
14332            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14333
14334            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14335                    receivers);
14336            if (comp == null) {
14337                continue;
14338            }
14339
14340            final int verifierUid = getUidForVerifier(verifierInfo);
14341            if (verifierUid == -1) {
14342                continue;
14343            }
14344
14345            if (DEBUG_VERIFY) {
14346                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14347                        + " with the correct signature");
14348            }
14349            sufficientVerifiers.add(comp);
14350            verificationState.addSufficientVerifier(verifierUid);
14351        }
14352
14353        return sufficientVerifiers;
14354    }
14355
14356    private int getUidForVerifier(VerifierInfo verifierInfo) {
14357        synchronized (mPackages) {
14358            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14359            if (pkg == null) {
14360                return -1;
14361            } else if (pkg.mSigningDetails.signatures.length != 1) {
14362                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14363                        + " has more than one signature; ignoring");
14364                return -1;
14365            }
14366
14367            /*
14368             * If the public key of the package's signature does not match
14369             * our expected public key, then this is a different package and
14370             * we should skip.
14371             */
14372
14373            final byte[] expectedPublicKey;
14374            try {
14375                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14376                final PublicKey publicKey = verifierSig.getPublicKey();
14377                expectedPublicKey = publicKey.getEncoded();
14378            } catch (CertificateException e) {
14379                return -1;
14380            }
14381
14382            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14383
14384            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14385                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14386                        + " does not have the expected public key; ignoring");
14387                return -1;
14388            }
14389
14390            return pkg.applicationInfo.uid;
14391        }
14392    }
14393
14394    @Override
14395    public void finishPackageInstall(int token, boolean didLaunch) {
14396        enforceSystemOrRoot("Only the system is allowed to finish installs");
14397
14398        if (DEBUG_INSTALL) {
14399            Slog.v(TAG, "BM finishing package install for " + token);
14400        }
14401        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14402
14403        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14404        mHandler.sendMessage(msg);
14405    }
14406
14407    /**
14408     * Get the verification agent timeout.  Used for both the APK verifier and the
14409     * intent filter verifier.
14410     *
14411     * @return verification timeout in milliseconds
14412     */
14413    private long getVerificationTimeout() {
14414        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14415                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14416                DEFAULT_VERIFICATION_TIMEOUT);
14417    }
14418
14419    /**
14420     * Get the default verification agent response code.
14421     *
14422     * @return default verification response code
14423     */
14424    private int getDefaultVerificationResponse(UserHandle user) {
14425        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14426            return PackageManager.VERIFICATION_REJECT;
14427        }
14428        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14429                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14430                DEFAULT_VERIFICATION_RESPONSE);
14431    }
14432
14433    /**
14434     * Check whether or not package verification has been enabled.
14435     *
14436     * @return true if verification should be performed
14437     */
14438    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14439        if (!DEFAULT_VERIFY_ENABLE) {
14440            return false;
14441        }
14442
14443        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14444
14445        // Check if installing from ADB
14446        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14447            // Do not run verification in a test harness environment
14448            if (ActivityManager.isRunningInTestHarness()) {
14449                return false;
14450            }
14451            if (ensureVerifyAppsEnabled) {
14452                return true;
14453            }
14454            // Check if the developer does not want package verification for ADB installs
14455            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14456                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14457                return false;
14458            }
14459        } else {
14460            // only when not installed from ADB, skip verification for instant apps when
14461            // the installer and verifier are the same.
14462            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14463                if (mInstantAppInstallerActivity != null
14464                        && mInstantAppInstallerActivity.packageName.equals(
14465                                mRequiredVerifierPackage)) {
14466                    try {
14467                        mContext.getSystemService(AppOpsManager.class)
14468                                .checkPackage(installerUid, mRequiredVerifierPackage);
14469                        if (DEBUG_VERIFY) {
14470                            Slog.i(TAG, "disable verification for instant app");
14471                        }
14472                        return false;
14473                    } catch (SecurityException ignore) { }
14474                }
14475            }
14476        }
14477
14478        if (ensureVerifyAppsEnabled) {
14479            return true;
14480        }
14481
14482        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14483                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14484    }
14485
14486    @Override
14487    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14488            throws RemoteException {
14489        mContext.enforceCallingOrSelfPermission(
14490                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14491                "Only intentfilter verification agents can verify applications");
14492
14493        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14494        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14495                Binder.getCallingUid(), verificationCode, failedDomains);
14496        msg.arg1 = id;
14497        msg.obj = response;
14498        mHandler.sendMessage(msg);
14499    }
14500
14501    @Override
14502    public int getIntentVerificationStatus(String packageName, int userId) {
14503        final int callingUid = Binder.getCallingUid();
14504        if (UserHandle.getUserId(callingUid) != userId) {
14505            mContext.enforceCallingOrSelfPermission(
14506                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14507                    "getIntentVerificationStatus" + userId);
14508        }
14509        if (getInstantAppPackageName(callingUid) != null) {
14510            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14511        }
14512        synchronized (mPackages) {
14513            final PackageSetting ps = mSettings.mPackages.get(packageName);
14514            if (ps == null
14515                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14516                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14517            }
14518            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14519        }
14520    }
14521
14522    @Override
14523    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14524        mContext.enforceCallingOrSelfPermission(
14525                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14526
14527        boolean result = false;
14528        synchronized (mPackages) {
14529            final PackageSetting ps = mSettings.mPackages.get(packageName);
14530            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14531                return false;
14532            }
14533            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14534        }
14535        if (result) {
14536            scheduleWritePackageRestrictionsLocked(userId);
14537        }
14538        return result;
14539    }
14540
14541    @Override
14542    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14543            String packageName) {
14544        final int callingUid = Binder.getCallingUid();
14545        if (getInstantAppPackageName(callingUid) != null) {
14546            return ParceledListSlice.emptyList();
14547        }
14548        synchronized (mPackages) {
14549            final PackageSetting ps = mSettings.mPackages.get(packageName);
14550            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14551                return ParceledListSlice.emptyList();
14552            }
14553            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14554        }
14555    }
14556
14557    @Override
14558    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14559        if (TextUtils.isEmpty(packageName)) {
14560            return ParceledListSlice.emptyList();
14561        }
14562        final int callingUid = Binder.getCallingUid();
14563        final int callingUserId = UserHandle.getUserId(callingUid);
14564        synchronized (mPackages) {
14565            PackageParser.Package pkg = mPackages.get(packageName);
14566            if (pkg == null || pkg.activities == null) {
14567                return ParceledListSlice.emptyList();
14568            }
14569            if (pkg.mExtras == null) {
14570                return ParceledListSlice.emptyList();
14571            }
14572            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14573            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14574                return ParceledListSlice.emptyList();
14575            }
14576            final int count = pkg.activities.size();
14577            ArrayList<IntentFilter> result = new ArrayList<>();
14578            for (int n=0; n<count; n++) {
14579                PackageParser.Activity activity = pkg.activities.get(n);
14580                if (activity.intents != null && activity.intents.size() > 0) {
14581                    result.addAll(activity.intents);
14582                }
14583            }
14584            return new ParceledListSlice<>(result);
14585        }
14586    }
14587
14588    @Override
14589    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14590        mContext.enforceCallingOrSelfPermission(
14591                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14592        if (UserHandle.getCallingUserId() != userId) {
14593            mContext.enforceCallingOrSelfPermission(
14594                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14595        }
14596
14597        synchronized (mPackages) {
14598            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14599            if (packageName != null) {
14600                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14601                        packageName, userId);
14602            }
14603            return result;
14604        }
14605    }
14606
14607    @Override
14608    public String getDefaultBrowserPackageName(int userId) {
14609        if (UserHandle.getCallingUserId() != userId) {
14610            mContext.enforceCallingOrSelfPermission(
14611                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14612        }
14613        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14614            return null;
14615        }
14616        synchronized (mPackages) {
14617            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14618        }
14619    }
14620
14621    /**
14622     * Get the "allow unknown sources" setting.
14623     *
14624     * @return the current "allow unknown sources" setting
14625     */
14626    private int getUnknownSourcesSettings() {
14627        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14628                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14629                -1);
14630    }
14631
14632    @Override
14633    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14634        final int callingUid = Binder.getCallingUid();
14635        if (getInstantAppPackageName(callingUid) != null) {
14636            return;
14637        }
14638        // writer
14639        synchronized (mPackages) {
14640            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14641            if (targetPackageSetting == null
14642                    || filterAppAccessLPr(
14643                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14644                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14645            }
14646
14647            PackageSetting installerPackageSetting;
14648            if (installerPackageName != null) {
14649                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14650                if (installerPackageSetting == null) {
14651                    throw new IllegalArgumentException("Unknown installer package: "
14652                            + installerPackageName);
14653                }
14654            } else {
14655                installerPackageSetting = null;
14656            }
14657
14658            Signature[] callerSignature;
14659            Object obj = mSettings.getUserIdLPr(callingUid);
14660            if (obj != null) {
14661                if (obj instanceof SharedUserSetting) {
14662                    callerSignature =
14663                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14664                } else if (obj instanceof PackageSetting) {
14665                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14666                } else {
14667                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14668                }
14669            } else {
14670                throw new SecurityException("Unknown calling UID: " + callingUid);
14671            }
14672
14673            // Verify: can't set installerPackageName to a package that is
14674            // not signed with the same cert as the caller.
14675            if (installerPackageSetting != null) {
14676                if (compareSignatures(callerSignature,
14677                        installerPackageSetting.signatures.mSigningDetails.signatures)
14678                        != PackageManager.SIGNATURE_MATCH) {
14679                    throw new SecurityException(
14680                            "Caller does not have same cert as new installer package "
14681                            + installerPackageName);
14682                }
14683            }
14684
14685            // Verify: if target already has an installer package, it must
14686            // be signed with the same cert as the caller.
14687            if (targetPackageSetting.installerPackageName != null) {
14688                PackageSetting setting = mSettings.mPackages.get(
14689                        targetPackageSetting.installerPackageName);
14690                // If the currently set package isn't valid, then it's always
14691                // okay to change it.
14692                if (setting != null) {
14693                    if (compareSignatures(callerSignature,
14694                            setting.signatures.mSigningDetails.signatures)
14695                            != PackageManager.SIGNATURE_MATCH) {
14696                        throw new SecurityException(
14697                                "Caller does not have same cert as old installer package "
14698                                + targetPackageSetting.installerPackageName);
14699                    }
14700                }
14701            }
14702
14703            // Okay!
14704            targetPackageSetting.installerPackageName = installerPackageName;
14705            if (installerPackageName != null) {
14706                mSettings.mInstallerPackages.add(installerPackageName);
14707            }
14708            scheduleWriteSettingsLocked();
14709        }
14710    }
14711
14712    @Override
14713    public void setApplicationCategoryHint(String packageName, int categoryHint,
14714            String callerPackageName) {
14715        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14716            throw new SecurityException("Instant applications don't have access to this method");
14717        }
14718        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14719                callerPackageName);
14720        synchronized (mPackages) {
14721            PackageSetting ps = mSettings.mPackages.get(packageName);
14722            if (ps == null) {
14723                throw new IllegalArgumentException("Unknown target package " + packageName);
14724            }
14725            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14726                throw new IllegalArgumentException("Unknown target package " + packageName);
14727            }
14728            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14729                throw new IllegalArgumentException("Calling package " + callerPackageName
14730                        + " is not installer for " + packageName);
14731            }
14732
14733            if (ps.categoryHint != categoryHint) {
14734                ps.categoryHint = categoryHint;
14735                scheduleWriteSettingsLocked();
14736            }
14737        }
14738    }
14739
14740    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14741        // Queue up an async operation since the package installation may take a little while.
14742        mHandler.post(new Runnable() {
14743            public void run() {
14744                mHandler.removeCallbacks(this);
14745                 // Result object to be returned
14746                PackageInstalledInfo res = new PackageInstalledInfo();
14747                res.setReturnCode(currentStatus);
14748                res.uid = -1;
14749                res.pkg = null;
14750                res.removedInfo = null;
14751                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14752                    args.doPreInstall(res.returnCode);
14753                    synchronized (mInstallLock) {
14754                        installPackageTracedLI(args, res);
14755                    }
14756                    args.doPostInstall(res.returnCode, res.uid);
14757                }
14758
14759                // A restore should be performed at this point if (a) the install
14760                // succeeded, (b) the operation is not an update, and (c) the new
14761                // package has not opted out of backup participation.
14762                final boolean update = res.removedInfo != null
14763                        && res.removedInfo.removedPackage != null;
14764                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14765                boolean doRestore = !update
14766                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14767
14768                // Set up the post-install work request bookkeeping.  This will be used
14769                // and cleaned up by the post-install event handling regardless of whether
14770                // there's a restore pass performed.  Token values are >= 1.
14771                int token;
14772                if (mNextInstallToken < 0) mNextInstallToken = 1;
14773                token = mNextInstallToken++;
14774
14775                PostInstallData data = new PostInstallData(args, res);
14776                mRunningInstalls.put(token, data);
14777                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14778
14779                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14780                    // Pass responsibility to the Backup Manager.  It will perform a
14781                    // restore if appropriate, then pass responsibility back to the
14782                    // Package Manager to run the post-install observer callbacks
14783                    // and broadcasts.
14784                    IBackupManager bm = IBackupManager.Stub.asInterface(
14785                            ServiceManager.getService(Context.BACKUP_SERVICE));
14786                    if (bm != null) {
14787                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14788                                + " to BM for possible restore");
14789                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14790                        try {
14791                            // TODO: http://b/22388012
14792                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14793                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14794                            } else {
14795                                doRestore = false;
14796                            }
14797                        } catch (RemoteException e) {
14798                            // can't happen; the backup manager is local
14799                        } catch (Exception e) {
14800                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14801                            doRestore = false;
14802                        }
14803                    } else {
14804                        Slog.e(TAG, "Backup Manager not found!");
14805                        doRestore = false;
14806                    }
14807                }
14808
14809                if (!doRestore) {
14810                    // No restore possible, or the Backup Manager was mysteriously not
14811                    // available -- just fire the post-install work request directly.
14812                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14813
14814                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14815
14816                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14817                    mHandler.sendMessage(msg);
14818                }
14819            }
14820        });
14821    }
14822
14823    /**
14824     * Callback from PackageSettings whenever an app is first transitioned out of the
14825     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14826     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14827     * here whether the app is the target of an ongoing install, and only send the
14828     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14829     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14830     * handling.
14831     */
14832    void notifyFirstLaunch(final String packageName, final String installerPackage,
14833            final int userId) {
14834        // Serialize this with the rest of the install-process message chain.  In the
14835        // restore-at-install case, this Runnable will necessarily run before the
14836        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14837        // are coherent.  In the non-restore case, the app has already completed install
14838        // and been launched through some other means, so it is not in a problematic
14839        // state for observers to see the FIRST_LAUNCH signal.
14840        mHandler.post(new Runnable() {
14841            @Override
14842            public void run() {
14843                for (int i = 0; i < mRunningInstalls.size(); i++) {
14844                    final PostInstallData data = mRunningInstalls.valueAt(i);
14845                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14846                        continue;
14847                    }
14848                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14849                        // right package; but is it for the right user?
14850                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14851                            if (userId == data.res.newUsers[uIndex]) {
14852                                if (DEBUG_BACKUP) {
14853                                    Slog.i(TAG, "Package " + packageName
14854                                            + " being restored so deferring FIRST_LAUNCH");
14855                                }
14856                                return;
14857                            }
14858                        }
14859                    }
14860                }
14861                // didn't find it, so not being restored
14862                if (DEBUG_BACKUP) {
14863                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14864                }
14865                final boolean isInstantApp = isInstantApp(packageName, userId);
14866                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14867                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14868                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14869            }
14870        });
14871    }
14872
14873    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14874            int[] userIds, int[] instantUserIds) {
14875        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14876                installerPkg, null, userIds, instantUserIds);
14877    }
14878
14879    private abstract class HandlerParams {
14880        private static final int MAX_RETRIES = 4;
14881
14882        /**
14883         * Number of times startCopy() has been attempted and had a non-fatal
14884         * error.
14885         */
14886        private int mRetries = 0;
14887
14888        /** User handle for the user requesting the information or installation. */
14889        private final UserHandle mUser;
14890        String traceMethod;
14891        int traceCookie;
14892
14893        HandlerParams(UserHandle user) {
14894            mUser = user;
14895        }
14896
14897        UserHandle getUser() {
14898            return mUser;
14899        }
14900
14901        HandlerParams setTraceMethod(String traceMethod) {
14902            this.traceMethod = traceMethod;
14903            return this;
14904        }
14905
14906        HandlerParams setTraceCookie(int traceCookie) {
14907            this.traceCookie = traceCookie;
14908            return this;
14909        }
14910
14911        final boolean startCopy() {
14912            boolean res;
14913            try {
14914                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14915
14916                if (++mRetries > MAX_RETRIES) {
14917                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14918                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14919                    handleServiceError();
14920                    return false;
14921                } else {
14922                    handleStartCopy();
14923                    res = true;
14924                }
14925            } catch (RemoteException e) {
14926                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14927                mHandler.sendEmptyMessage(MCS_RECONNECT);
14928                res = false;
14929            }
14930            handleReturnCode();
14931            return res;
14932        }
14933
14934        final void serviceError() {
14935            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14936            handleServiceError();
14937            handleReturnCode();
14938        }
14939
14940        abstract void handleStartCopy() throws RemoteException;
14941        abstract void handleServiceError();
14942        abstract void handleReturnCode();
14943    }
14944
14945    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14946        for (File path : paths) {
14947            try {
14948                mcs.clearDirectory(path.getAbsolutePath());
14949            } catch (RemoteException e) {
14950            }
14951        }
14952    }
14953
14954    static class OriginInfo {
14955        /**
14956         * Location where install is coming from, before it has been
14957         * copied/renamed into place. This could be a single monolithic APK
14958         * file, or a cluster directory. This location may be untrusted.
14959         */
14960        final File file;
14961
14962        /**
14963         * Flag indicating that {@link #file} or {@link #cid} has already been
14964         * staged, meaning downstream users don't need to defensively copy the
14965         * contents.
14966         */
14967        final boolean staged;
14968
14969        /**
14970         * Flag indicating that {@link #file} or {@link #cid} is an already
14971         * installed app that is being moved.
14972         */
14973        final boolean existing;
14974
14975        final String resolvedPath;
14976        final File resolvedFile;
14977
14978        static OriginInfo fromNothing() {
14979            return new OriginInfo(null, false, false);
14980        }
14981
14982        static OriginInfo fromUntrustedFile(File file) {
14983            return new OriginInfo(file, false, false);
14984        }
14985
14986        static OriginInfo fromExistingFile(File file) {
14987            return new OriginInfo(file, false, true);
14988        }
14989
14990        static OriginInfo fromStagedFile(File file) {
14991            return new OriginInfo(file, true, false);
14992        }
14993
14994        private OriginInfo(File file, boolean staged, boolean existing) {
14995            this.file = file;
14996            this.staged = staged;
14997            this.existing = existing;
14998
14999            if (file != null) {
15000                resolvedPath = file.getAbsolutePath();
15001                resolvedFile = file;
15002            } else {
15003                resolvedPath = null;
15004                resolvedFile = null;
15005            }
15006        }
15007    }
15008
15009    static class MoveInfo {
15010        final int moveId;
15011        final String fromUuid;
15012        final String toUuid;
15013        final String packageName;
15014        final String dataAppName;
15015        final int appId;
15016        final String seinfo;
15017        final int targetSdkVersion;
15018
15019        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15020                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15021            this.moveId = moveId;
15022            this.fromUuid = fromUuid;
15023            this.toUuid = toUuid;
15024            this.packageName = packageName;
15025            this.dataAppName = dataAppName;
15026            this.appId = appId;
15027            this.seinfo = seinfo;
15028            this.targetSdkVersion = targetSdkVersion;
15029        }
15030    }
15031
15032    static class VerificationInfo {
15033        /** A constant used to indicate that a uid value is not present. */
15034        public static final int NO_UID = -1;
15035
15036        /** URI referencing where the package was downloaded from. */
15037        final Uri originatingUri;
15038
15039        /** HTTP referrer URI associated with the originatingURI. */
15040        final Uri referrer;
15041
15042        /** UID of the application that the install request originated from. */
15043        final int originatingUid;
15044
15045        /** UID of application requesting the install */
15046        final int installerUid;
15047
15048        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15049            this.originatingUri = originatingUri;
15050            this.referrer = referrer;
15051            this.originatingUid = originatingUid;
15052            this.installerUid = installerUid;
15053        }
15054    }
15055
15056    class InstallParams extends HandlerParams {
15057        final OriginInfo origin;
15058        final MoveInfo move;
15059        final IPackageInstallObserver2 observer;
15060        int installFlags;
15061        final String installerPackageName;
15062        final String volumeUuid;
15063        private InstallArgs mArgs;
15064        private int mRet;
15065        final String packageAbiOverride;
15066        final String[] grantedRuntimePermissions;
15067        final VerificationInfo verificationInfo;
15068        final PackageParser.SigningDetails signingDetails;
15069        final int installReason;
15070
15071        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15072                int installFlags, String installerPackageName, String volumeUuid,
15073                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15074                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15075            super(user);
15076            this.origin = origin;
15077            this.move = move;
15078            this.observer = observer;
15079            this.installFlags = installFlags;
15080            this.installerPackageName = installerPackageName;
15081            this.volumeUuid = volumeUuid;
15082            this.verificationInfo = verificationInfo;
15083            this.packageAbiOverride = packageAbiOverride;
15084            this.grantedRuntimePermissions = grantedPermissions;
15085            this.signingDetails = signingDetails;
15086            this.installReason = installReason;
15087        }
15088
15089        @Override
15090        public String toString() {
15091            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15092                    + " file=" + origin.file + "}";
15093        }
15094
15095        private int installLocationPolicy(PackageInfoLite pkgLite) {
15096            String packageName = pkgLite.packageName;
15097            int installLocation = pkgLite.installLocation;
15098            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15099            // reader
15100            synchronized (mPackages) {
15101                // Currently installed package which the new package is attempting to replace or
15102                // null if no such package is installed.
15103                PackageParser.Package installedPkg = mPackages.get(packageName);
15104                // Package which currently owns the data which the new package will own if installed.
15105                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15106                // will be null whereas dataOwnerPkg will contain information about the package
15107                // which was uninstalled while keeping its data.
15108                PackageParser.Package dataOwnerPkg = installedPkg;
15109                if (dataOwnerPkg  == null) {
15110                    PackageSetting ps = mSettings.mPackages.get(packageName);
15111                    if (ps != null) {
15112                        dataOwnerPkg = ps.pkg;
15113                    }
15114                }
15115
15116                if (dataOwnerPkg != null) {
15117                    // If installed, the package will get access to data left on the device by its
15118                    // predecessor. As a security measure, this is permited only if this is not a
15119                    // version downgrade or if the predecessor package is marked as debuggable and
15120                    // a downgrade is explicitly requested.
15121                    //
15122                    // On debuggable platform builds, downgrades are permitted even for
15123                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15124                    // not offer security guarantees and thus it's OK to disable some security
15125                    // mechanisms to make debugging/testing easier on those builds. However, even on
15126                    // debuggable builds downgrades of packages are permitted only if requested via
15127                    // installFlags. This is because we aim to keep the behavior of debuggable
15128                    // platform builds as close as possible to the behavior of non-debuggable
15129                    // platform builds.
15130                    final boolean downgradeRequested =
15131                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15132                    final boolean packageDebuggable =
15133                                (dataOwnerPkg.applicationInfo.flags
15134                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15135                    final boolean downgradePermitted =
15136                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15137                    if (!downgradePermitted) {
15138                        try {
15139                            checkDowngrade(dataOwnerPkg, pkgLite);
15140                        } catch (PackageManagerException e) {
15141                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15142                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15143                        }
15144                    }
15145                }
15146
15147                if (installedPkg != null) {
15148                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15149                        // Check for updated system application.
15150                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15151                            if (onSd) {
15152                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15153                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15154                            }
15155                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15156                        } else {
15157                            if (onSd) {
15158                                // Install flag overrides everything.
15159                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15160                            }
15161                            // If current upgrade specifies particular preference
15162                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15163                                // Application explicitly specified internal.
15164                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15165                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15166                                // App explictly prefers external. Let policy decide
15167                            } else {
15168                                // Prefer previous location
15169                                if (isExternal(installedPkg)) {
15170                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15171                                }
15172                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15173                            }
15174                        }
15175                    } else {
15176                        // Invalid install. Return error code
15177                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15178                    }
15179                }
15180            }
15181            // All the special cases have been taken care of.
15182            // Return result based on recommended install location.
15183            if (onSd) {
15184                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15185            }
15186            return pkgLite.recommendedInstallLocation;
15187        }
15188
15189        /*
15190         * Invoke remote method to get package information and install
15191         * location values. Override install location based on default
15192         * policy if needed and then create install arguments based
15193         * on the install location.
15194         */
15195        public void handleStartCopy() throws RemoteException {
15196            int ret = PackageManager.INSTALL_SUCCEEDED;
15197
15198            // If we're already staged, we've firmly committed to an install location
15199            if (origin.staged) {
15200                if (origin.file != null) {
15201                    installFlags |= PackageManager.INSTALL_INTERNAL;
15202                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15203                } else {
15204                    throw new IllegalStateException("Invalid stage location");
15205                }
15206            }
15207
15208            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15209            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15210            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15211            PackageInfoLite pkgLite = null;
15212
15213            if (onInt && onSd) {
15214                // Check if both bits are set.
15215                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15216                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15217            } else if (onSd && ephemeral) {
15218                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15219                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15220            } else {
15221                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15222                        packageAbiOverride);
15223
15224                if (DEBUG_INSTANT && ephemeral) {
15225                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15226                }
15227
15228                /*
15229                 * If we have too little free space, try to free cache
15230                 * before giving up.
15231                 */
15232                if (!origin.staged && pkgLite.recommendedInstallLocation
15233                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15234                    // TODO: focus freeing disk space on the target device
15235                    final StorageManager storage = StorageManager.from(mContext);
15236                    final long lowThreshold = storage.getStorageLowBytes(
15237                            Environment.getDataDirectory());
15238
15239                    final long sizeBytes = mContainerService.calculateInstalledSize(
15240                            origin.resolvedPath, packageAbiOverride);
15241
15242                    try {
15243                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15244                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15245                                installFlags, packageAbiOverride);
15246                    } catch (InstallerException e) {
15247                        Slog.w(TAG, "Failed to free cache", e);
15248                    }
15249
15250                    /*
15251                     * The cache free must have deleted the file we
15252                     * downloaded to install.
15253                     *
15254                     * TODO: fix the "freeCache" call to not delete
15255                     *       the file we care about.
15256                     */
15257                    if (pkgLite.recommendedInstallLocation
15258                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15259                        pkgLite.recommendedInstallLocation
15260                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15261                    }
15262                }
15263            }
15264
15265            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15266                int loc = pkgLite.recommendedInstallLocation;
15267                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15268                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15269                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15270                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15271                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15272                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15273                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15274                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15275                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15276                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15277                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15278                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15279                } else {
15280                    // Override with defaults if needed.
15281                    loc = installLocationPolicy(pkgLite);
15282                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15283                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15284                    } else if (!onSd && !onInt) {
15285                        // Override install location with flags
15286                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15287                            // Set the flag to install on external media.
15288                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15289                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15290                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15291                            if (DEBUG_INSTANT) {
15292                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15293                            }
15294                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15295                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15296                                    |PackageManager.INSTALL_INTERNAL);
15297                        } else {
15298                            // Make sure the flag for installing on external
15299                            // media is unset
15300                            installFlags |= PackageManager.INSTALL_INTERNAL;
15301                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15302                        }
15303                    }
15304                }
15305            }
15306
15307            final InstallArgs args = createInstallArgs(this);
15308            mArgs = args;
15309
15310            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15311                // TODO: http://b/22976637
15312                // Apps installed for "all" users use the device owner to verify the app
15313                UserHandle verifierUser = getUser();
15314                if (verifierUser == UserHandle.ALL) {
15315                    verifierUser = UserHandle.SYSTEM;
15316                }
15317
15318                /*
15319                 * Determine if we have any installed package verifiers. If we
15320                 * do, then we'll defer to them to verify the packages.
15321                 */
15322                final int requiredUid = mRequiredVerifierPackage == null ? -1
15323                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15324                                verifierUser.getIdentifier());
15325                final int installerUid =
15326                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15327                if (!origin.existing && requiredUid != -1
15328                        && isVerificationEnabled(
15329                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15330                    final Intent verification = new Intent(
15331                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15332                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15333                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15334                            PACKAGE_MIME_TYPE);
15335                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15336
15337                    // Query all live verifiers based on current user state
15338                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15339                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15340                            false /*allowDynamicSplits*/);
15341
15342                    if (DEBUG_VERIFY) {
15343                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15344                                + verification.toString() + " with " + pkgLite.verifiers.length
15345                                + " optional verifiers");
15346                    }
15347
15348                    final int verificationId = mPendingVerificationToken++;
15349
15350                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15351
15352                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15353                            installerPackageName);
15354
15355                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15356                            installFlags);
15357
15358                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15359                            pkgLite.packageName);
15360
15361                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15362                            pkgLite.versionCode);
15363
15364                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15365                            pkgLite.getLongVersionCode());
15366
15367                    if (verificationInfo != null) {
15368                        if (verificationInfo.originatingUri != null) {
15369                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15370                                    verificationInfo.originatingUri);
15371                        }
15372                        if (verificationInfo.referrer != null) {
15373                            verification.putExtra(Intent.EXTRA_REFERRER,
15374                                    verificationInfo.referrer);
15375                        }
15376                        if (verificationInfo.originatingUid >= 0) {
15377                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15378                                    verificationInfo.originatingUid);
15379                        }
15380                        if (verificationInfo.installerUid >= 0) {
15381                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15382                                    verificationInfo.installerUid);
15383                        }
15384                    }
15385
15386                    final PackageVerificationState verificationState = new PackageVerificationState(
15387                            requiredUid, args);
15388
15389                    mPendingVerification.append(verificationId, verificationState);
15390
15391                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15392                            receivers, verificationState);
15393
15394                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15395                    final long idleDuration = getVerificationTimeout();
15396
15397                    /*
15398                     * If any sufficient verifiers were listed in the package
15399                     * manifest, attempt to ask them.
15400                     */
15401                    if (sufficientVerifiers != null) {
15402                        final int N = sufficientVerifiers.size();
15403                        if (N == 0) {
15404                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15405                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15406                        } else {
15407                            for (int i = 0; i < N; i++) {
15408                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15409                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15410                                        verifierComponent.getPackageName(), idleDuration,
15411                                        verifierUser.getIdentifier(), false, "package verifier");
15412
15413                                final Intent sufficientIntent = new Intent(verification);
15414                                sufficientIntent.setComponent(verifierComponent);
15415                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15416                            }
15417                        }
15418                    }
15419
15420                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15421                            mRequiredVerifierPackage, receivers);
15422                    if (ret == PackageManager.INSTALL_SUCCEEDED
15423                            && mRequiredVerifierPackage != null) {
15424                        Trace.asyncTraceBegin(
15425                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15426                        /*
15427                         * Send the intent to the required verification agent,
15428                         * but only start the verification timeout after the
15429                         * target BroadcastReceivers have run.
15430                         */
15431                        verification.setComponent(requiredVerifierComponent);
15432                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15433                                mRequiredVerifierPackage, idleDuration,
15434                                verifierUser.getIdentifier(), false, "package verifier");
15435                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15436                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15437                                new BroadcastReceiver() {
15438                                    @Override
15439                                    public void onReceive(Context context, Intent intent) {
15440                                        final Message msg = mHandler
15441                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15442                                        msg.arg1 = verificationId;
15443                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15444                                    }
15445                                }, null, 0, null, null);
15446
15447                        /*
15448                         * We don't want the copy to proceed until verification
15449                         * succeeds, so null out this field.
15450                         */
15451                        mArgs = null;
15452                    }
15453                } else {
15454                    /*
15455                     * No package verification is enabled, so immediately start
15456                     * the remote call to initiate copy using temporary file.
15457                     */
15458                    ret = args.copyApk(mContainerService, true);
15459                }
15460            }
15461
15462            mRet = ret;
15463        }
15464
15465        @Override
15466        void handleReturnCode() {
15467            // If mArgs is null, then MCS couldn't be reached. When it
15468            // reconnects, it will try again to install. At that point, this
15469            // will succeed.
15470            if (mArgs != null) {
15471                processPendingInstall(mArgs, mRet);
15472            }
15473        }
15474
15475        @Override
15476        void handleServiceError() {
15477            mArgs = createInstallArgs(this);
15478            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15479        }
15480    }
15481
15482    private InstallArgs createInstallArgs(InstallParams params) {
15483        if (params.move != null) {
15484            return new MoveInstallArgs(params);
15485        } else {
15486            return new FileInstallArgs(params);
15487        }
15488    }
15489
15490    /**
15491     * Create args that describe an existing installed package. Typically used
15492     * when cleaning up old installs, or used as a move source.
15493     */
15494    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15495            String resourcePath, String[] instructionSets) {
15496        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15497    }
15498
15499    static abstract class InstallArgs {
15500        /** @see InstallParams#origin */
15501        final OriginInfo origin;
15502        /** @see InstallParams#move */
15503        final MoveInfo move;
15504
15505        final IPackageInstallObserver2 observer;
15506        // Always refers to PackageManager flags only
15507        final int installFlags;
15508        final String installerPackageName;
15509        final String volumeUuid;
15510        final UserHandle user;
15511        final String abiOverride;
15512        final String[] installGrantPermissions;
15513        /** If non-null, drop an async trace when the install completes */
15514        final String traceMethod;
15515        final int traceCookie;
15516        final PackageParser.SigningDetails signingDetails;
15517        final int installReason;
15518
15519        // The list of instruction sets supported by this app. This is currently
15520        // only used during the rmdex() phase to clean up resources. We can get rid of this
15521        // if we move dex files under the common app path.
15522        /* nullable */ String[] instructionSets;
15523
15524        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15525                int installFlags, String installerPackageName, String volumeUuid,
15526                UserHandle user, String[] instructionSets,
15527                String abiOverride, String[] installGrantPermissions,
15528                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15529                int installReason) {
15530            this.origin = origin;
15531            this.move = move;
15532            this.installFlags = installFlags;
15533            this.observer = observer;
15534            this.installerPackageName = installerPackageName;
15535            this.volumeUuid = volumeUuid;
15536            this.user = user;
15537            this.instructionSets = instructionSets;
15538            this.abiOverride = abiOverride;
15539            this.installGrantPermissions = installGrantPermissions;
15540            this.traceMethod = traceMethod;
15541            this.traceCookie = traceCookie;
15542            this.signingDetails = signingDetails;
15543            this.installReason = installReason;
15544        }
15545
15546        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15547        abstract int doPreInstall(int status);
15548
15549        /**
15550         * Rename package into final resting place. All paths on the given
15551         * scanned package should be updated to reflect the rename.
15552         */
15553        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15554        abstract int doPostInstall(int status, int uid);
15555
15556        /** @see PackageSettingBase#codePathString */
15557        abstract String getCodePath();
15558        /** @see PackageSettingBase#resourcePathString */
15559        abstract String getResourcePath();
15560
15561        // Need installer lock especially for dex file removal.
15562        abstract void cleanUpResourcesLI();
15563        abstract boolean doPostDeleteLI(boolean delete);
15564
15565        /**
15566         * Called before the source arguments are copied. This is used mostly
15567         * for MoveParams when it needs to read the source file to put it in the
15568         * destination.
15569         */
15570        int doPreCopy() {
15571            return PackageManager.INSTALL_SUCCEEDED;
15572        }
15573
15574        /**
15575         * Called after the source arguments are copied. This is used mostly for
15576         * MoveParams when it needs to read the source file to put it in the
15577         * destination.
15578         */
15579        int doPostCopy(int uid) {
15580            return PackageManager.INSTALL_SUCCEEDED;
15581        }
15582
15583        protected boolean isFwdLocked() {
15584            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15585        }
15586
15587        protected boolean isExternalAsec() {
15588            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15589        }
15590
15591        protected boolean isEphemeral() {
15592            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15593        }
15594
15595        UserHandle getUser() {
15596            return user;
15597        }
15598    }
15599
15600    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15601        if (!allCodePaths.isEmpty()) {
15602            if (instructionSets == null) {
15603                throw new IllegalStateException("instructionSet == null");
15604            }
15605            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15606            for (String codePath : allCodePaths) {
15607                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15608                    try {
15609                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15610                    } catch (InstallerException ignored) {
15611                    }
15612                }
15613            }
15614        }
15615    }
15616
15617    /**
15618     * Logic to handle installation of non-ASEC applications, including copying
15619     * and renaming logic.
15620     */
15621    class FileInstallArgs extends InstallArgs {
15622        private File codeFile;
15623        private File resourceFile;
15624
15625        // Example topology:
15626        // /data/app/com.example/base.apk
15627        // /data/app/com.example/split_foo.apk
15628        // /data/app/com.example/lib/arm/libfoo.so
15629        // /data/app/com.example/lib/arm64/libfoo.so
15630        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15631
15632        /** New install */
15633        FileInstallArgs(InstallParams params) {
15634            super(params.origin, params.move, params.observer, params.installFlags,
15635                    params.installerPackageName, params.volumeUuid,
15636                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15637                    params.grantedRuntimePermissions,
15638                    params.traceMethod, params.traceCookie, params.signingDetails,
15639                    params.installReason);
15640            if (isFwdLocked()) {
15641                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15642            }
15643        }
15644
15645        /** Existing install */
15646        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15647            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15648                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15649                    PackageManager.INSTALL_REASON_UNKNOWN);
15650            this.codeFile = (codePath != null) ? new File(codePath) : null;
15651            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15652        }
15653
15654        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15655            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15656            try {
15657                return doCopyApk(imcs, temp);
15658            } finally {
15659                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15660            }
15661        }
15662
15663        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15664            if (origin.staged) {
15665                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15666                codeFile = origin.file;
15667                resourceFile = origin.file;
15668                return PackageManager.INSTALL_SUCCEEDED;
15669            }
15670
15671            try {
15672                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15673                final File tempDir =
15674                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15675                codeFile = tempDir;
15676                resourceFile = tempDir;
15677            } catch (IOException e) {
15678                Slog.w(TAG, "Failed to create copy file: " + e);
15679                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15680            }
15681
15682            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15683                @Override
15684                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15685                    if (!FileUtils.isValidExtFilename(name)) {
15686                        throw new IllegalArgumentException("Invalid filename: " + name);
15687                    }
15688                    try {
15689                        final File file = new File(codeFile, name);
15690                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15691                                O_RDWR | O_CREAT, 0644);
15692                        Os.chmod(file.getAbsolutePath(), 0644);
15693                        return new ParcelFileDescriptor(fd);
15694                    } catch (ErrnoException e) {
15695                        throw new RemoteException("Failed to open: " + e.getMessage());
15696                    }
15697                }
15698            };
15699
15700            int ret = PackageManager.INSTALL_SUCCEEDED;
15701            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15702            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15703                Slog.e(TAG, "Failed to copy package");
15704                return ret;
15705            }
15706
15707            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15708            NativeLibraryHelper.Handle handle = null;
15709            try {
15710                handle = NativeLibraryHelper.Handle.create(codeFile);
15711                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15712                        abiOverride);
15713            } catch (IOException e) {
15714                Slog.e(TAG, "Copying native libraries failed", e);
15715                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15716            } finally {
15717                IoUtils.closeQuietly(handle);
15718            }
15719
15720            return ret;
15721        }
15722
15723        int doPreInstall(int status) {
15724            if (status != PackageManager.INSTALL_SUCCEEDED) {
15725                cleanUp();
15726            }
15727            return status;
15728        }
15729
15730        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15731            if (status != PackageManager.INSTALL_SUCCEEDED) {
15732                cleanUp();
15733                return false;
15734            }
15735
15736            final File targetDir = codeFile.getParentFile();
15737            final File beforeCodeFile = codeFile;
15738            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15739
15740            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15741            try {
15742                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15743            } catch (ErrnoException e) {
15744                Slog.w(TAG, "Failed to rename", e);
15745                return false;
15746            }
15747
15748            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15749                Slog.w(TAG, "Failed to restorecon");
15750                return false;
15751            }
15752
15753            // Reflect the rename internally
15754            codeFile = afterCodeFile;
15755            resourceFile = afterCodeFile;
15756
15757            // Reflect the rename in scanned details
15758            try {
15759                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15760            } catch (IOException e) {
15761                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15762                return false;
15763            }
15764            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15765                    afterCodeFile, pkg.baseCodePath));
15766            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15767                    afterCodeFile, pkg.splitCodePaths));
15768
15769            // Reflect the rename in app info
15770            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15771            pkg.setApplicationInfoCodePath(pkg.codePath);
15772            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15773            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15774            pkg.setApplicationInfoResourcePath(pkg.codePath);
15775            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15776            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15777
15778            return true;
15779        }
15780
15781        int doPostInstall(int status, int uid) {
15782            if (status != PackageManager.INSTALL_SUCCEEDED) {
15783                cleanUp();
15784            }
15785            return status;
15786        }
15787
15788        @Override
15789        String getCodePath() {
15790            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15791        }
15792
15793        @Override
15794        String getResourcePath() {
15795            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15796        }
15797
15798        private boolean cleanUp() {
15799            if (codeFile == null || !codeFile.exists()) {
15800                return false;
15801            }
15802
15803            removeCodePathLI(codeFile);
15804
15805            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15806                resourceFile.delete();
15807            }
15808
15809            return true;
15810        }
15811
15812        void cleanUpResourcesLI() {
15813            // Try enumerating all code paths before deleting
15814            List<String> allCodePaths = Collections.EMPTY_LIST;
15815            if (codeFile != null && codeFile.exists()) {
15816                try {
15817                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15818                    allCodePaths = pkg.getAllCodePaths();
15819                } catch (PackageParserException e) {
15820                    // Ignored; we tried our best
15821                }
15822            }
15823
15824            cleanUp();
15825            removeDexFiles(allCodePaths, instructionSets);
15826        }
15827
15828        boolean doPostDeleteLI(boolean delete) {
15829            // XXX err, shouldn't we respect the delete flag?
15830            cleanUpResourcesLI();
15831            return true;
15832        }
15833    }
15834
15835    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15836            PackageManagerException {
15837        if (copyRet < 0) {
15838            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15839                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15840                throw new PackageManagerException(copyRet, message);
15841            }
15842        }
15843    }
15844
15845    /**
15846     * Extract the StorageManagerService "container ID" from the full code path of an
15847     * .apk.
15848     */
15849    static String cidFromCodePath(String fullCodePath) {
15850        int eidx = fullCodePath.lastIndexOf("/");
15851        String subStr1 = fullCodePath.substring(0, eidx);
15852        int sidx = subStr1.lastIndexOf("/");
15853        return subStr1.substring(sidx+1, eidx);
15854    }
15855
15856    /**
15857     * Logic to handle movement of existing installed applications.
15858     */
15859    class MoveInstallArgs extends InstallArgs {
15860        private File codeFile;
15861        private File resourceFile;
15862
15863        /** New install */
15864        MoveInstallArgs(InstallParams params) {
15865            super(params.origin, params.move, params.observer, params.installFlags,
15866                    params.installerPackageName, params.volumeUuid,
15867                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15868                    params.grantedRuntimePermissions,
15869                    params.traceMethod, params.traceCookie, params.signingDetails,
15870                    params.installReason);
15871        }
15872
15873        int copyApk(IMediaContainerService imcs, boolean temp) {
15874            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15875                    + move.fromUuid + " to " + move.toUuid);
15876            synchronized (mInstaller) {
15877                try {
15878                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15879                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15880                } catch (InstallerException e) {
15881                    Slog.w(TAG, "Failed to move app", e);
15882                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15883                }
15884            }
15885
15886            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15887            resourceFile = codeFile;
15888            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15889
15890            return PackageManager.INSTALL_SUCCEEDED;
15891        }
15892
15893        int doPreInstall(int status) {
15894            if (status != PackageManager.INSTALL_SUCCEEDED) {
15895                cleanUp(move.toUuid);
15896            }
15897            return status;
15898        }
15899
15900        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15901            if (status != PackageManager.INSTALL_SUCCEEDED) {
15902                cleanUp(move.toUuid);
15903                return false;
15904            }
15905
15906            // Reflect the move in app info
15907            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15908            pkg.setApplicationInfoCodePath(pkg.codePath);
15909            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15910            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15911            pkg.setApplicationInfoResourcePath(pkg.codePath);
15912            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15913            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15914
15915            return true;
15916        }
15917
15918        int doPostInstall(int status, int uid) {
15919            if (status == PackageManager.INSTALL_SUCCEEDED) {
15920                cleanUp(move.fromUuid);
15921            } else {
15922                cleanUp(move.toUuid);
15923            }
15924            return status;
15925        }
15926
15927        @Override
15928        String getCodePath() {
15929            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15930        }
15931
15932        @Override
15933        String getResourcePath() {
15934            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15935        }
15936
15937        private boolean cleanUp(String volumeUuid) {
15938            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15939                    move.dataAppName);
15940            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15941            final int[] userIds = sUserManager.getUserIds();
15942            synchronized (mInstallLock) {
15943                // Clean up both app data and code
15944                // All package moves are frozen until finished
15945                for (int userId : userIds) {
15946                    try {
15947                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15948                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15949                    } catch (InstallerException e) {
15950                        Slog.w(TAG, String.valueOf(e));
15951                    }
15952                }
15953                removeCodePathLI(codeFile);
15954            }
15955            return true;
15956        }
15957
15958        void cleanUpResourcesLI() {
15959            throw new UnsupportedOperationException();
15960        }
15961
15962        boolean doPostDeleteLI(boolean delete) {
15963            throw new UnsupportedOperationException();
15964        }
15965    }
15966
15967    static String getAsecPackageName(String packageCid) {
15968        int idx = packageCid.lastIndexOf("-");
15969        if (idx == -1) {
15970            return packageCid;
15971        }
15972        return packageCid.substring(0, idx);
15973    }
15974
15975    // Utility method used to create code paths based on package name and available index.
15976    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15977        String idxStr = "";
15978        int idx = 1;
15979        // Fall back to default value of idx=1 if prefix is not
15980        // part of oldCodePath
15981        if (oldCodePath != null) {
15982            String subStr = oldCodePath;
15983            // Drop the suffix right away
15984            if (suffix != null && subStr.endsWith(suffix)) {
15985                subStr = subStr.substring(0, subStr.length() - suffix.length());
15986            }
15987            // If oldCodePath already contains prefix find out the
15988            // ending index to either increment or decrement.
15989            int sidx = subStr.lastIndexOf(prefix);
15990            if (sidx != -1) {
15991                subStr = subStr.substring(sidx + prefix.length());
15992                if (subStr != null) {
15993                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15994                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15995                    }
15996                    try {
15997                        idx = Integer.parseInt(subStr);
15998                        if (idx <= 1) {
15999                            idx++;
16000                        } else {
16001                            idx--;
16002                        }
16003                    } catch(NumberFormatException e) {
16004                    }
16005                }
16006            }
16007        }
16008        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16009        return prefix + idxStr;
16010    }
16011
16012    private File getNextCodePath(File targetDir, String packageName) {
16013        File result;
16014        SecureRandom random = new SecureRandom();
16015        byte[] bytes = new byte[16];
16016        do {
16017            random.nextBytes(bytes);
16018            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16019            result = new File(targetDir, packageName + "-" + suffix);
16020        } while (result.exists());
16021        return result;
16022    }
16023
16024    // Utility method that returns the relative package path with respect
16025    // to the installation directory. Like say for /data/data/com.test-1.apk
16026    // string com.test-1 is returned.
16027    static String deriveCodePathName(String codePath) {
16028        if (codePath == null) {
16029            return null;
16030        }
16031        final File codeFile = new File(codePath);
16032        final String name = codeFile.getName();
16033        if (codeFile.isDirectory()) {
16034            return name;
16035        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16036            final int lastDot = name.lastIndexOf('.');
16037            return name.substring(0, lastDot);
16038        } else {
16039            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16040            return null;
16041        }
16042    }
16043
16044    static class PackageInstalledInfo {
16045        String name;
16046        int uid;
16047        // The set of users that originally had this package installed.
16048        int[] origUsers;
16049        // The set of users that now have this package installed.
16050        int[] newUsers;
16051        PackageParser.Package pkg;
16052        int returnCode;
16053        String returnMsg;
16054        String installerPackageName;
16055        PackageRemovedInfo removedInfo;
16056        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16057
16058        public void setError(int code, String msg) {
16059            setReturnCode(code);
16060            setReturnMessage(msg);
16061            Slog.w(TAG, msg);
16062        }
16063
16064        public void setError(String msg, PackageParserException e) {
16065            setReturnCode(e.error);
16066            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16067            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16068            for (int i = 0; i < childCount; i++) {
16069                addedChildPackages.valueAt(i).setError(msg, e);
16070            }
16071            Slog.w(TAG, msg, e);
16072        }
16073
16074        public void setError(String msg, PackageManagerException e) {
16075            returnCode = e.error;
16076            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16077            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16078            for (int i = 0; i < childCount; i++) {
16079                addedChildPackages.valueAt(i).setError(msg, e);
16080            }
16081            Slog.w(TAG, msg, e);
16082        }
16083
16084        public void setReturnCode(int returnCode) {
16085            this.returnCode = returnCode;
16086            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16087            for (int i = 0; i < childCount; i++) {
16088                addedChildPackages.valueAt(i).returnCode = returnCode;
16089            }
16090        }
16091
16092        private void setReturnMessage(String returnMsg) {
16093            this.returnMsg = returnMsg;
16094            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16095            for (int i = 0; i < childCount; i++) {
16096                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16097            }
16098        }
16099
16100        // In some error cases we want to convey more info back to the observer
16101        String origPackage;
16102        String origPermission;
16103    }
16104
16105    /*
16106     * Install a non-existing package.
16107     */
16108    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16109            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16110            String volumeUuid, PackageInstalledInfo res, int installReason) {
16111        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16112
16113        // Remember this for later, in case we need to rollback this install
16114        String pkgName = pkg.packageName;
16115
16116        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16117
16118        synchronized(mPackages) {
16119            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16120            if (renamedPackage != null) {
16121                // A package with the same name is already installed, though
16122                // it has been renamed to an older name.  The package we
16123                // are trying to install should be installed as an update to
16124                // the existing one, but that has not been requested, so bail.
16125                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16126                        + " without first uninstalling package running as "
16127                        + renamedPackage);
16128                return;
16129            }
16130            if (mPackages.containsKey(pkgName)) {
16131                // Don't allow installation over an existing package with the same name.
16132                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16133                        + " without first uninstalling.");
16134                return;
16135            }
16136        }
16137
16138        try {
16139            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16140                    System.currentTimeMillis(), user);
16141
16142            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16143
16144            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16145                prepareAppDataAfterInstallLIF(newPackage);
16146
16147            } else {
16148                // Remove package from internal structures, but keep around any
16149                // data that might have already existed
16150                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16151                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16152            }
16153        } catch (PackageManagerException e) {
16154            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16155        }
16156
16157        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16158    }
16159
16160    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16161        try (DigestInputStream digestStream =
16162                new DigestInputStream(new FileInputStream(file), digest)) {
16163            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16164        }
16165    }
16166
16167    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16168            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16169            PackageInstalledInfo res, int installReason) {
16170        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16171
16172        final PackageParser.Package oldPackage;
16173        final PackageSetting ps;
16174        final String pkgName = pkg.packageName;
16175        final int[] allUsers;
16176        final int[] installedUsers;
16177
16178        synchronized(mPackages) {
16179            oldPackage = mPackages.get(pkgName);
16180            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16181
16182            // don't allow upgrade to target a release SDK from a pre-release SDK
16183            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16184                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16185            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16186                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16187            if (oldTargetsPreRelease
16188                    && !newTargetsPreRelease
16189                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16190                Slog.w(TAG, "Can't install package targeting released sdk");
16191                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16192                return;
16193            }
16194
16195            ps = mSettings.mPackages.get(pkgName);
16196
16197            // verify signatures are valid
16198            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16199            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16200                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16201                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16202                            "New package not signed by keys specified by upgrade-keysets: "
16203                                    + pkgName);
16204                    return;
16205                }
16206            } else {
16207
16208                // default to original signature matching
16209                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16210                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
16211                                && !oldPackage.mSigningDetails.checkCapability(
16212                                        pkg.mSigningDetails,
16213                                        PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
16214                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16215                            "New package has a different signature: " + pkgName);
16216                    return;
16217                }
16218            }
16219
16220            // don't allow a system upgrade unless the upgrade hash matches
16221            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16222                byte[] digestBytes = null;
16223                try {
16224                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16225                    updateDigest(digest, new File(pkg.baseCodePath));
16226                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16227                        for (String path : pkg.splitCodePaths) {
16228                            updateDigest(digest, new File(path));
16229                        }
16230                    }
16231                    digestBytes = digest.digest();
16232                } catch (NoSuchAlgorithmException | IOException e) {
16233                    res.setError(INSTALL_FAILED_INVALID_APK,
16234                            "Could not compute hash: " + pkgName);
16235                    return;
16236                }
16237                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16238                    res.setError(INSTALL_FAILED_INVALID_APK,
16239                            "New package fails restrict-update check: " + pkgName);
16240                    return;
16241                }
16242                // retain upgrade restriction
16243                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16244            }
16245
16246            // Check for shared user id changes
16247            String invalidPackageName =
16248                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16249            if (invalidPackageName != null) {
16250                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16251                        "Package " + invalidPackageName + " tried to change user "
16252                                + oldPackage.mSharedUserId);
16253                return;
16254            }
16255
16256            // check if the new package supports all of the abis which the old package supports
16257            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16258            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16259            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16260                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16261                        "Update to package " + pkgName + " doesn't support multi arch");
16262                return;
16263            }
16264
16265            // In case of rollback, remember per-user/profile install state
16266            allUsers = sUserManager.getUserIds();
16267            installedUsers = ps.queryInstalledUsers(allUsers, true);
16268
16269            // don't allow an upgrade from full to ephemeral
16270            if (isInstantApp) {
16271                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16272                    for (int currentUser : allUsers) {
16273                        if (!ps.getInstantApp(currentUser)) {
16274                            // can't downgrade from full to instant
16275                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16276                                    + " for user: " + currentUser);
16277                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16278                            return;
16279                        }
16280                    }
16281                } else if (!ps.getInstantApp(user.getIdentifier())) {
16282                    // can't downgrade from full to instant
16283                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16284                            + " for user: " + user.getIdentifier());
16285                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16286                    return;
16287                }
16288            }
16289        }
16290
16291        // Update what is removed
16292        res.removedInfo = new PackageRemovedInfo(this);
16293        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16294        res.removedInfo.removedPackage = oldPackage.packageName;
16295        res.removedInfo.installerPackageName = ps.installerPackageName;
16296        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16297        res.removedInfo.isUpdate = true;
16298        res.removedInfo.origUsers = installedUsers;
16299        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16300        for (int i = 0; i < installedUsers.length; i++) {
16301            final int userId = installedUsers[i];
16302            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16303        }
16304
16305        final int childCount = (oldPackage.childPackages != null)
16306                ? oldPackage.childPackages.size() : 0;
16307        for (int i = 0; i < childCount; i++) {
16308            boolean childPackageUpdated = false;
16309            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16310            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16311            if (res.addedChildPackages != null) {
16312                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16313                if (childRes != null) {
16314                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16315                    childRes.removedInfo.removedPackage = childPkg.packageName;
16316                    if (childPs != null) {
16317                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16318                    }
16319                    childRes.removedInfo.isUpdate = true;
16320                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16321                    childPackageUpdated = true;
16322                }
16323            }
16324            if (!childPackageUpdated) {
16325                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16326                childRemovedRes.removedPackage = childPkg.packageName;
16327                if (childPs != null) {
16328                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16329                }
16330                childRemovedRes.isUpdate = false;
16331                childRemovedRes.dataRemoved = true;
16332                synchronized (mPackages) {
16333                    if (childPs != null) {
16334                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16335                    }
16336                }
16337                if (res.removedInfo.removedChildPackages == null) {
16338                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16339                }
16340                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16341            }
16342        }
16343
16344        boolean sysPkg = (isSystemApp(oldPackage));
16345        if (sysPkg) {
16346            // Set the system/privileged/oem/vendor/product flags as needed
16347            final boolean privileged =
16348                    (oldPackage.applicationInfo.privateFlags
16349                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16350            final boolean oem =
16351                    (oldPackage.applicationInfo.privateFlags
16352                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16353            final boolean vendor =
16354                    (oldPackage.applicationInfo.privateFlags
16355                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16356            final boolean product =
16357                    (oldPackage.applicationInfo.privateFlags
16358                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16359            final @ParseFlags int systemParseFlags = parseFlags;
16360            final @ScanFlags int systemScanFlags = scanFlags
16361                    | SCAN_AS_SYSTEM
16362                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16363                    | (oem ? SCAN_AS_OEM : 0)
16364                    | (vendor ? SCAN_AS_VENDOR : 0)
16365                    | (product ? SCAN_AS_PRODUCT : 0);
16366
16367            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16368                    user, allUsers, installerPackageName, res, installReason);
16369        } else {
16370            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16371                    user, allUsers, installerPackageName, res, installReason);
16372        }
16373    }
16374
16375    @Override
16376    public List<String> getPreviousCodePaths(String packageName) {
16377        final int callingUid = Binder.getCallingUid();
16378        final List<String> result = new ArrayList<>();
16379        if (getInstantAppPackageName(callingUid) != null) {
16380            return result;
16381        }
16382        final PackageSetting ps = mSettings.mPackages.get(packageName);
16383        if (ps != null
16384                && ps.oldCodePaths != null
16385                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16386            result.addAll(ps.oldCodePaths);
16387        }
16388        return result;
16389    }
16390
16391    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16392            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16393            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16394            String installerPackageName, PackageInstalledInfo res, int installReason) {
16395        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16396                + deletedPackage);
16397
16398        String pkgName = deletedPackage.packageName;
16399        boolean deletedPkg = true;
16400        boolean addedPkg = false;
16401        boolean updatedSettings = false;
16402        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16403        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16404                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16405
16406        final long origUpdateTime = (pkg.mExtras != null)
16407                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16408
16409        // First delete the existing package while retaining the data directory
16410        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16411                res.removedInfo, true, pkg)) {
16412            // If the existing package wasn't successfully deleted
16413            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16414            deletedPkg = false;
16415        } else {
16416            // Successfully deleted the old package; proceed with replace.
16417
16418            // If deleted package lived in a container, give users a chance to
16419            // relinquish resources before killing.
16420            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16421                if (DEBUG_INSTALL) {
16422                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16423                }
16424                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16425                final ArrayList<String> pkgList = new ArrayList<String>(1);
16426                pkgList.add(deletedPackage.applicationInfo.packageName);
16427                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16428            }
16429
16430            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16431                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16432
16433            try {
16434                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16435                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16436                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16437                        installReason);
16438
16439                // Update the in-memory copy of the previous code paths.
16440                PackageSetting ps = mSettings.mPackages.get(pkgName);
16441                if (!killApp) {
16442                    if (ps.oldCodePaths == null) {
16443                        ps.oldCodePaths = new ArraySet<>();
16444                    }
16445                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16446                    if (deletedPackage.splitCodePaths != null) {
16447                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16448                    }
16449                } else {
16450                    ps.oldCodePaths = null;
16451                }
16452                if (ps.childPackageNames != null) {
16453                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16454                        final String childPkgName = ps.childPackageNames.get(i);
16455                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16456                        childPs.oldCodePaths = ps.oldCodePaths;
16457                    }
16458                }
16459                prepareAppDataAfterInstallLIF(newPackage);
16460                addedPkg = true;
16461                mDexManager.notifyPackageUpdated(newPackage.packageName,
16462                        newPackage.baseCodePath, newPackage.splitCodePaths);
16463            } catch (PackageManagerException e) {
16464                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16465            }
16466        }
16467
16468        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16469            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16470
16471            // Revert all internal state mutations and added folders for the failed install
16472            if (addedPkg) {
16473                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16474                        res.removedInfo, true, null);
16475            }
16476
16477            // Restore the old package
16478            if (deletedPkg) {
16479                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16480                File restoreFile = new File(deletedPackage.codePath);
16481                // Parse old package
16482                boolean oldExternal = isExternal(deletedPackage);
16483                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16484                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16485                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16486                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16487                try {
16488                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16489                            null);
16490                } catch (PackageManagerException e) {
16491                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16492                            + e.getMessage());
16493                    return;
16494                }
16495
16496                synchronized (mPackages) {
16497                    // Ensure the installer package name up to date
16498                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16499
16500                    // Update permissions for restored package
16501                    mPermissionManager.updatePermissions(
16502                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16503                            mPermissionCallback);
16504
16505                    mSettings.writeLPr();
16506                }
16507
16508                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16509            }
16510        } else {
16511            synchronized (mPackages) {
16512                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16513                if (ps != null) {
16514                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16515                    if (res.removedInfo.removedChildPackages != null) {
16516                        final int childCount = res.removedInfo.removedChildPackages.size();
16517                        // Iterate in reverse as we may modify the collection
16518                        for (int i = childCount - 1; i >= 0; i--) {
16519                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16520                            if (res.addedChildPackages.containsKey(childPackageName)) {
16521                                res.removedInfo.removedChildPackages.removeAt(i);
16522                            } else {
16523                                PackageRemovedInfo childInfo = res.removedInfo
16524                                        .removedChildPackages.valueAt(i);
16525                                childInfo.removedForAllUsers = mPackages.get(
16526                                        childInfo.removedPackage) == null;
16527                            }
16528                        }
16529                    }
16530                }
16531            }
16532        }
16533    }
16534
16535    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16536            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16537            final @ScanFlags int scanFlags, UserHandle user,
16538            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16539            int installReason) {
16540        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16541                + ", old=" + deletedPackage);
16542
16543        final boolean disabledSystem;
16544
16545        // Remove existing system package
16546        removePackageLI(deletedPackage, true);
16547
16548        synchronized (mPackages) {
16549            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16550        }
16551        if (!disabledSystem) {
16552            // We didn't need to disable the .apk as a current system package,
16553            // which means we are replacing another update that is already
16554            // installed.  We need to make sure to delete the older one's .apk.
16555            res.removedInfo.args = createInstallArgsForExisting(0,
16556                    deletedPackage.applicationInfo.getCodePath(),
16557                    deletedPackage.applicationInfo.getResourcePath(),
16558                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16559        } else {
16560            res.removedInfo.args = null;
16561        }
16562
16563        // Successfully disabled the old package. Now proceed with re-installation
16564        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16565                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16566
16567        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16568        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16569                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16570
16571        PackageParser.Package newPackage = null;
16572        try {
16573            // Add the package to the internal data structures
16574            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16575
16576            // Set the update and install times
16577            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16578            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16579                    System.currentTimeMillis());
16580
16581            // Update the package dynamic state if succeeded
16582            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16583                // Now that the install succeeded make sure we remove data
16584                // directories for any child package the update removed.
16585                final int deletedChildCount = (deletedPackage.childPackages != null)
16586                        ? deletedPackage.childPackages.size() : 0;
16587                final int newChildCount = (newPackage.childPackages != null)
16588                        ? newPackage.childPackages.size() : 0;
16589                for (int i = 0; i < deletedChildCount; i++) {
16590                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16591                    boolean childPackageDeleted = true;
16592                    for (int j = 0; j < newChildCount; j++) {
16593                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16594                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16595                            childPackageDeleted = false;
16596                            break;
16597                        }
16598                    }
16599                    if (childPackageDeleted) {
16600                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16601                                deletedChildPkg.packageName);
16602                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16603                            PackageRemovedInfo removedChildRes = res.removedInfo
16604                                    .removedChildPackages.get(deletedChildPkg.packageName);
16605                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16606                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16607                        }
16608                    }
16609                }
16610
16611                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16612                        installReason);
16613                prepareAppDataAfterInstallLIF(newPackage);
16614
16615                mDexManager.notifyPackageUpdated(newPackage.packageName,
16616                            newPackage.baseCodePath, newPackage.splitCodePaths);
16617            }
16618        } catch (PackageManagerException e) {
16619            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16620            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16621        }
16622
16623        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16624            // Re installation failed. Restore old information
16625            // Remove new pkg information
16626            if (newPackage != null) {
16627                removeInstalledPackageLI(newPackage, true);
16628            }
16629            // Add back the old system package
16630            try {
16631                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16632            } catch (PackageManagerException e) {
16633                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16634            }
16635
16636            synchronized (mPackages) {
16637                if (disabledSystem) {
16638                    enableSystemPackageLPw(deletedPackage);
16639                }
16640
16641                // Ensure the installer package name up to date
16642                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16643
16644                // Update permissions for restored package
16645                mPermissionManager.updatePermissions(
16646                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16647                        mPermissionCallback);
16648
16649                mSettings.writeLPr();
16650            }
16651
16652            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16653                    + " after failed upgrade");
16654        }
16655    }
16656
16657    /**
16658     * Checks whether the parent or any of the child packages have a change shared
16659     * user. For a package to be a valid update the shred users of the parent and
16660     * the children should match. We may later support changing child shared users.
16661     * @param oldPkg The updated package.
16662     * @param newPkg The update package.
16663     * @return The shared user that change between the versions.
16664     */
16665    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16666            PackageParser.Package newPkg) {
16667        // Check parent shared user
16668        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16669            return newPkg.packageName;
16670        }
16671        // Check child shared users
16672        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16673        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16674        for (int i = 0; i < newChildCount; i++) {
16675            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16676            // If this child was present, did it have the same shared user?
16677            for (int j = 0; j < oldChildCount; j++) {
16678                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16679                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16680                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16681                    return newChildPkg.packageName;
16682                }
16683            }
16684        }
16685        return null;
16686    }
16687
16688    private void removeNativeBinariesLI(PackageSetting ps) {
16689        // Remove the lib path for the parent package
16690        if (ps != null) {
16691            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16692            // Remove the lib path for the child packages
16693            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16694            for (int i = 0; i < childCount; i++) {
16695                PackageSetting childPs = null;
16696                synchronized (mPackages) {
16697                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16698                }
16699                if (childPs != null) {
16700                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16701                            .legacyNativeLibraryPathString);
16702                }
16703            }
16704        }
16705    }
16706
16707    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16708        // Enable the parent package
16709        mSettings.enableSystemPackageLPw(pkg.packageName);
16710        // Enable the child packages
16711        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16712        for (int i = 0; i < childCount; i++) {
16713            PackageParser.Package childPkg = pkg.childPackages.get(i);
16714            mSettings.enableSystemPackageLPw(childPkg.packageName);
16715        }
16716    }
16717
16718    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16719            PackageParser.Package newPkg) {
16720        // Disable the parent package (parent always replaced)
16721        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16722        // Disable the child packages
16723        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16724        for (int i = 0; i < childCount; i++) {
16725            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16726            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16727            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16728        }
16729        return disabled;
16730    }
16731
16732    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16733            String installerPackageName) {
16734        // Enable the parent package
16735        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16736        // Enable the child packages
16737        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16738        for (int i = 0; i < childCount; i++) {
16739            PackageParser.Package childPkg = pkg.childPackages.get(i);
16740            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16741        }
16742    }
16743
16744    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16745            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16746        // Update the parent package setting
16747        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16748                res, user, installReason);
16749        // Update the child packages setting
16750        final int childCount = (newPackage.childPackages != null)
16751                ? newPackage.childPackages.size() : 0;
16752        for (int i = 0; i < childCount; i++) {
16753            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16754            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16755            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16756                    childRes.origUsers, childRes, user, installReason);
16757        }
16758    }
16759
16760    private void updateSettingsInternalLI(PackageParser.Package pkg,
16761            String installerPackageName, int[] allUsers, int[] installedForUsers,
16762            PackageInstalledInfo res, UserHandle user, int installReason) {
16763        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16764
16765        final String pkgName = pkg.packageName;
16766
16767        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16768        synchronized (mPackages) {
16769// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16770            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16771                    mPermissionCallback);
16772            // For system-bundled packages, we assume that installing an upgraded version
16773            // of the package implies that the user actually wants to run that new code,
16774            // so we enable the package.
16775            PackageSetting ps = mSettings.mPackages.get(pkgName);
16776            final int userId = user.getIdentifier();
16777            if (ps != null) {
16778                if (isSystemApp(pkg)) {
16779                    if (DEBUG_INSTALL) {
16780                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16781                    }
16782                    // Enable system package for requested users
16783                    if (res.origUsers != null) {
16784                        for (int origUserId : res.origUsers) {
16785                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16786                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16787                                        origUserId, installerPackageName);
16788                            }
16789                        }
16790                    }
16791                    // Also convey the prior install/uninstall state
16792                    if (allUsers != null && installedForUsers != null) {
16793                        for (int currentUserId : allUsers) {
16794                            final boolean installed = ArrayUtils.contains(
16795                                    installedForUsers, currentUserId);
16796                            if (DEBUG_INSTALL) {
16797                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16798                            }
16799                            ps.setInstalled(installed, currentUserId);
16800                        }
16801                        // these install state changes will be persisted in the
16802                        // upcoming call to mSettings.writeLPr().
16803                    }
16804                }
16805                // It's implied that when a user requests installation, they want the app to be
16806                // installed and enabled.
16807                if (userId != UserHandle.USER_ALL) {
16808                    ps.setInstalled(true, userId);
16809                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16810                }
16811
16812                // When replacing an existing package, preserve the original install reason for all
16813                // users that had the package installed before.
16814                final Set<Integer> previousUserIds = new ArraySet<>();
16815                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16816                    final int installReasonCount = res.removedInfo.installReasons.size();
16817                    for (int i = 0; i < installReasonCount; i++) {
16818                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16819                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16820                        ps.setInstallReason(previousInstallReason, previousUserId);
16821                        previousUserIds.add(previousUserId);
16822                    }
16823                }
16824
16825                // Set install reason for users that are having the package newly installed.
16826                if (userId == UserHandle.USER_ALL) {
16827                    for (int currentUserId : sUserManager.getUserIds()) {
16828                        if (!previousUserIds.contains(currentUserId)) {
16829                            ps.setInstallReason(installReason, currentUserId);
16830                        }
16831                    }
16832                } else if (!previousUserIds.contains(userId)) {
16833                    ps.setInstallReason(installReason, userId);
16834                }
16835                mSettings.writeKernelMappingLPr(ps);
16836            }
16837            res.name = pkgName;
16838            res.uid = pkg.applicationInfo.uid;
16839            res.pkg = pkg;
16840            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16841            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16842            //to update install status
16843            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16844            mSettings.writeLPr();
16845            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16846        }
16847
16848        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16849    }
16850
16851    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16852        try {
16853            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16854            installPackageLI(args, res);
16855        } finally {
16856            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16857        }
16858    }
16859
16860    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16861        final int installFlags = args.installFlags;
16862        final String installerPackageName = args.installerPackageName;
16863        final String volumeUuid = args.volumeUuid;
16864        final File tmpPackageFile = new File(args.getCodePath());
16865        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16866        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16867                || (args.volumeUuid != null));
16868        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16869        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16870        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16871        final boolean virtualPreload =
16872                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16873        boolean replace = false;
16874        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16875        if (args.move != null) {
16876            // moving a complete application; perform an initial scan on the new install location
16877            scanFlags |= SCAN_INITIAL;
16878        }
16879        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16880            scanFlags |= SCAN_DONT_KILL_APP;
16881        }
16882        if (instantApp) {
16883            scanFlags |= SCAN_AS_INSTANT_APP;
16884        }
16885        if (fullApp) {
16886            scanFlags |= SCAN_AS_FULL_APP;
16887        }
16888        if (virtualPreload) {
16889            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16890        }
16891
16892        // Result object to be returned
16893        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16894        res.installerPackageName = installerPackageName;
16895
16896        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16897
16898        // Sanity check
16899        if (instantApp && (forwardLocked || onExternal)) {
16900            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16901                    + " external=" + onExternal);
16902            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16903            return;
16904        }
16905
16906        // Retrieve PackageSettings and parse package
16907        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16908                | PackageParser.PARSE_ENFORCE_CODE
16909                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16910                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16911                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16912        PackageParser pp = new PackageParser();
16913        pp.setSeparateProcesses(mSeparateProcesses);
16914        pp.setDisplayMetrics(mMetrics);
16915        pp.setCallback(mPackageParserCallback);
16916
16917        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16918        final PackageParser.Package pkg;
16919        try {
16920            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16921            DexMetadataHelper.validatePackageDexMetadata(pkg);
16922        } catch (PackageParserException e) {
16923            res.setError("Failed parse during installPackageLI", e);
16924            return;
16925        } finally {
16926            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16927        }
16928
16929        // Instant apps have several additional install-time checks.
16930        if (instantApp) {
16931            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16932                Slog.w(TAG,
16933                        "Instant app package " + pkg.packageName + " does not target at least O");
16934                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16935                        "Instant app package must target at least O");
16936                return;
16937            }
16938            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16939                Slog.w(TAG, "Instant app package " + pkg.packageName
16940                        + " does not target targetSandboxVersion 2");
16941                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16942                        "Instant app package must use targetSandboxVersion 2");
16943                return;
16944            }
16945            if (pkg.mSharedUserId != null) {
16946                Slog.w(TAG, "Instant app package " + pkg.packageName
16947                        + " may not declare sharedUserId.");
16948                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16949                        "Instant app package may not declare a sharedUserId");
16950                return;
16951            }
16952        }
16953
16954        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16955            // Static shared libraries have synthetic package names
16956            renameStaticSharedLibraryPackage(pkg);
16957
16958            // No static shared libs on external storage
16959            if (onExternal) {
16960                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16961                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16962                        "Packages declaring static-shared libs cannot be updated");
16963                return;
16964            }
16965        }
16966
16967        // If we are installing a clustered package add results for the children
16968        if (pkg.childPackages != null) {
16969            synchronized (mPackages) {
16970                final int childCount = pkg.childPackages.size();
16971                for (int i = 0; i < childCount; i++) {
16972                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16973                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16974                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16975                    childRes.pkg = childPkg;
16976                    childRes.name = childPkg.packageName;
16977                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16978                    if (childPs != null) {
16979                        childRes.origUsers = childPs.queryInstalledUsers(
16980                                sUserManager.getUserIds(), true);
16981                    }
16982                    if ((mPackages.containsKey(childPkg.packageName))) {
16983                        childRes.removedInfo = new PackageRemovedInfo(this);
16984                        childRes.removedInfo.removedPackage = childPkg.packageName;
16985                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16986                    }
16987                    if (res.addedChildPackages == null) {
16988                        res.addedChildPackages = new ArrayMap<>();
16989                    }
16990                    res.addedChildPackages.put(childPkg.packageName, childRes);
16991                }
16992            }
16993        }
16994
16995        // If package doesn't declare API override, mark that we have an install
16996        // time CPU ABI override.
16997        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16998            pkg.cpuAbiOverride = args.abiOverride;
16999        }
17000
17001        String pkgName = res.name = pkg.packageName;
17002        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17003            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17004                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17005                return;
17006            }
17007        }
17008
17009        try {
17010            // either use what we've been given or parse directly from the APK
17011            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17012                pkg.setSigningDetails(args.signingDetails);
17013            } else {
17014                PackageParser.collectCertificates(pkg, false /* skipVerify */);
17015            }
17016        } catch (PackageParserException e) {
17017            res.setError("Failed collect during installPackageLI", e);
17018            return;
17019        }
17020
17021        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17022                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17023            Slog.w(TAG, "Instant app package " + pkg.packageName
17024                    + " is not signed with at least APK Signature Scheme v2");
17025            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17026                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
17027            return;
17028        }
17029
17030        // Get rid of all references to package scan path via parser.
17031        pp = null;
17032        String oldCodePath = null;
17033        boolean systemApp = false;
17034        synchronized (mPackages) {
17035            // Check if installing already existing package
17036            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17037                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17038                if (pkg.mOriginalPackages != null
17039                        && pkg.mOriginalPackages.contains(oldName)
17040                        && mPackages.containsKey(oldName)) {
17041                    // This package is derived from an original package,
17042                    // and this device has been updating from that original
17043                    // name.  We must continue using the original name, so
17044                    // rename the new package here.
17045                    pkg.setPackageName(oldName);
17046                    pkgName = pkg.packageName;
17047                    replace = true;
17048                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17049                            + oldName + " pkgName=" + pkgName);
17050                } else if (mPackages.containsKey(pkgName)) {
17051                    // This package, under its official name, already exists
17052                    // on the device; we should replace it.
17053                    replace = true;
17054                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17055                }
17056
17057                // Child packages are installed through the parent package
17058                if (pkg.parentPackage != null) {
17059                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17060                            "Package " + pkg.packageName + " is child of package "
17061                                    + pkg.parentPackage.parentPackage + ". Child packages "
17062                                    + "can be updated only through the parent package.");
17063                    return;
17064                }
17065
17066                if (replace) {
17067                    // Prevent apps opting out from runtime permissions
17068                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17069                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17070                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17071                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17072                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17073                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17074                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17075                                        + " doesn't support runtime permissions but the old"
17076                                        + " target SDK " + oldTargetSdk + " does.");
17077                        return;
17078                    }
17079                    // Prevent persistent apps from being updated
17080                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17081                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17082                                "Package " + oldPackage.packageName + " is a persistent app. "
17083                                        + "Persistent apps are not updateable.");
17084                        return;
17085                    }
17086                    // Prevent apps from downgrading their targetSandbox.
17087                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17088                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17089                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17090                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17091                                "Package " + pkg.packageName + " new target sandbox "
17092                                + newTargetSandbox + " is incompatible with the previous value of"
17093                                + oldTargetSandbox + ".");
17094                        return;
17095                    }
17096
17097                    // Prevent installing of child packages
17098                    if (oldPackage.parentPackage != null) {
17099                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17100                                "Package " + pkg.packageName + " is child of package "
17101                                        + oldPackage.parentPackage + ". Child packages "
17102                                        + "can be updated only through the parent package.");
17103                        return;
17104                    }
17105                }
17106            }
17107
17108            PackageSetting ps = mSettings.mPackages.get(pkgName);
17109            if (ps != null) {
17110                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17111
17112                // Static shared libs have same package with different versions where
17113                // we internally use a synthetic package name to allow multiple versions
17114                // of the same package, therefore we need to compare signatures against
17115                // the package setting for the latest library version.
17116                PackageSetting signatureCheckPs = ps;
17117                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17118                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17119                    if (libraryEntry != null) {
17120                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17121                    }
17122                }
17123
17124                // Quick sanity check that we're signed correctly if updating;
17125                // we'll check this again later when scanning, but we want to
17126                // bail early here before tripping over redefined permissions.
17127                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17128                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17129                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17130                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17131                                + pkg.packageName + " upgrade keys do not match the "
17132                                + "previously installed version");
17133                        return;
17134                    }
17135                } else {
17136                    try {
17137                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17138                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17139                        // We don't care about disabledPkgSetting on install for now.
17140                        final boolean compatMatch = verifySignatures(
17141                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17142                                compareRecover);
17143                        // The new KeySets will be re-added later in the scanning process.
17144                        if (compatMatch) {
17145                            synchronized (mPackages) {
17146                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17147                            }
17148                        }
17149                    } catch (PackageManagerException e) {
17150                        res.setError(e.error, e.getMessage());
17151                        return;
17152                    }
17153                }
17154
17155                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17156                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17157                    systemApp = (ps.pkg.applicationInfo.flags &
17158                            ApplicationInfo.FLAG_SYSTEM) != 0;
17159                }
17160                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17161            }
17162
17163            int N = pkg.permissions.size();
17164            for (int i = N-1; i >= 0; i--) {
17165                final PackageParser.Permission perm = pkg.permissions.get(i);
17166                final BasePermission bp =
17167                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17168
17169                // Don't allow anyone but the system to define ephemeral permissions.
17170                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17171                        && !systemApp) {
17172                    Slog.w(TAG, "Non-System package " + pkg.packageName
17173                            + " attempting to delcare ephemeral permission "
17174                            + perm.info.name + "; Removing ephemeral.");
17175                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17176                }
17177
17178                // Check whether the newly-scanned package wants to define an already-defined perm
17179                if (bp != null) {
17180                    // If the defining package is signed with our cert, it's okay.  This
17181                    // also includes the "updating the same package" case, of course.
17182                    // "updating same package" could also involve key-rotation.
17183                    final boolean sigsOk;
17184                    final String sourcePackageName = bp.getSourcePackageName();
17185                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17186                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17187                    if (sourcePackageName.equals(pkg.packageName)
17188                            && (ksms.shouldCheckUpgradeKeySetLocked(
17189                                    sourcePackageSetting, scanFlags))) {
17190                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17191                    } else {
17192
17193                        // in the event of signing certificate rotation, we need to see if the
17194                        // package's certificate has rotated from the current one, or if it is an
17195                        // older certificate with which the current is ok with sharing permissions
17196                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17197                                        pkg.mSigningDetails,
17198                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17199                            sigsOk = true;
17200                        } else if (pkg.mSigningDetails.checkCapability(
17201                                        sourcePackageSetting.signatures.mSigningDetails,
17202                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17203
17204                            // the scanned package checks out, has signing certificate rotation
17205                            // history, and is newer; bring it over
17206                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17207                            sigsOk = true;
17208                        } else {
17209                            sigsOk = false;
17210                        }
17211                    }
17212                    if (!sigsOk) {
17213                        // If the owning package is the system itself, we log but allow
17214                        // install to proceed; we fail the install on all other permission
17215                        // redefinitions.
17216                        if (!sourcePackageName.equals("android")) {
17217                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17218                                    + pkg.packageName + " attempting to redeclare permission "
17219                                    + perm.info.name + " already owned by " + sourcePackageName);
17220                            res.origPermission = perm.info.name;
17221                            res.origPackage = sourcePackageName;
17222                            return;
17223                        } else {
17224                            Slog.w(TAG, "Package " + pkg.packageName
17225                                    + " attempting to redeclare system permission "
17226                                    + perm.info.name + "; ignoring new declaration");
17227                            pkg.permissions.remove(i);
17228                        }
17229                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17230                        // Prevent apps to change protection level to dangerous from any other
17231                        // type as this would allow a privilege escalation where an app adds a
17232                        // normal/signature permission in other app's group and later redefines
17233                        // it as dangerous leading to the group auto-grant.
17234                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17235                                == PermissionInfo.PROTECTION_DANGEROUS) {
17236                            if (bp != null && !bp.isRuntime()) {
17237                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17238                                        + "non-runtime permission " + perm.info.name
17239                                        + " to runtime; keeping old protection level");
17240                                perm.info.protectionLevel = bp.getProtectionLevel();
17241                            }
17242                        }
17243                    }
17244                }
17245            }
17246        }
17247
17248        if (systemApp) {
17249            if (onExternal) {
17250                // Abort update; system app can't be replaced with app on sdcard
17251                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17252                        "Cannot install updates to system apps on sdcard");
17253                return;
17254            } else if (instantApp) {
17255                // Abort update; system app can't be replaced with an instant app
17256                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17257                        "Cannot update a system app with an instant app");
17258                return;
17259            }
17260        }
17261
17262        if (args.move != null) {
17263            // We did an in-place move, so dex is ready to roll
17264            scanFlags |= SCAN_NO_DEX;
17265            scanFlags |= SCAN_MOVE;
17266
17267            synchronized (mPackages) {
17268                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17269                if (ps == null) {
17270                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17271                            "Missing settings for moved package " + pkgName);
17272                }
17273
17274                // We moved the entire application as-is, so bring over the
17275                // previously derived ABI information.
17276                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17277                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17278            }
17279
17280        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17281            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17282            scanFlags |= SCAN_NO_DEX;
17283
17284            try {
17285                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17286                    args.abiOverride : pkg.cpuAbiOverride);
17287                final boolean extractNativeLibs = !pkg.isLibrary();
17288                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17289            } catch (PackageManagerException pme) {
17290                Slog.e(TAG, "Error deriving application ABI", pme);
17291                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17292                return;
17293            }
17294
17295            // Shared libraries for the package need to be updated.
17296            synchronized (mPackages) {
17297                try {
17298                    updateSharedLibrariesLPr(pkg, null);
17299                } catch (PackageManagerException e) {
17300                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17301                }
17302            }
17303        }
17304
17305        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17306            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17307            return;
17308        }
17309
17310        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17311            String apkPath = null;
17312            synchronized (mPackages) {
17313                // Note that if the attacker managed to skip verify setup, for example by tampering
17314                // with the package settings, upon reboot we will do full apk verification when
17315                // verity is not detected.
17316                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17317                if (ps != null && ps.isPrivileged()) {
17318                    apkPath = pkg.baseCodePath;
17319                }
17320            }
17321
17322            if (apkPath != null) {
17323                final VerityUtils.SetupResult result =
17324                        VerityUtils.generateApkVeritySetupData(apkPath);
17325                if (result.isOk()) {
17326                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17327                    FileDescriptor fd = result.getUnownedFileDescriptor();
17328                    try {
17329                        final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath);
17330                        mInstaller.installApkVerity(apkPath, fd, result.getContentSize());
17331                        mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash);
17332                    } catch (InstallerException | IOException | DigestException |
17333                             NoSuchAlgorithmException e) {
17334                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17335                                "Failed to set up verity: " + e);
17336                        return;
17337                    } finally {
17338                        IoUtils.closeQuietly(fd);
17339                    }
17340                } else if (result.isFailed()) {
17341                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17342                    return;
17343                } else {
17344                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17345                    // reboot.
17346                }
17347            }
17348        }
17349
17350        if (!instantApp) {
17351            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17352        } else {
17353            if (DEBUG_DOMAIN_VERIFICATION) {
17354                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17355            }
17356        }
17357
17358        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17359                "installPackageLI")) {
17360            if (replace) {
17361                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17362                    // Static libs have a synthetic package name containing the version
17363                    // and cannot be updated as an update would get a new package name,
17364                    // unless this is the exact same version code which is useful for
17365                    // development.
17366                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17367                    if (existingPkg != null &&
17368                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17369                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17370                                + "static-shared libs cannot be updated");
17371                        return;
17372                    }
17373                }
17374                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17375                        installerPackageName, res, args.installReason);
17376            } else {
17377                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17378                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17379            }
17380        }
17381
17382        // Prepare the application profiles for the new code paths.
17383        // This needs to be done before invoking dexopt so that any install-time profile
17384        // can be used for optimizations.
17385        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17386
17387        // Check whether we need to dexopt the app.
17388        //
17389        // NOTE: it is IMPORTANT to call dexopt:
17390        //   - after doRename which will sync the package data from PackageParser.Package and its
17391        //     corresponding ApplicationInfo.
17392        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17393        //     uid of the application (pkg.applicationInfo.uid).
17394        //     This update happens in place!
17395        //
17396        // We only need to dexopt if the package meets ALL of the following conditions:
17397        //   1) it is not forward locked.
17398        //   2) it is not on on an external ASEC container.
17399        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17400        //
17401        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17402        // complete, so we skip this step during installation. Instead, we'll take extra time
17403        // the first time the instant app starts. It's preferred to do it this way to provide
17404        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17405        // middle of running an instant app. The default behaviour can be overridden
17406        // via gservices.
17407        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17408                && !forwardLocked
17409                && !pkg.applicationInfo.isExternalAsec()
17410                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17411                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17412
17413        if (performDexopt) {
17414            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17415            // Do not run PackageDexOptimizer through the local performDexOpt
17416            // method because `pkg` may not be in `mPackages` yet.
17417            //
17418            // Also, don't fail application installs if the dexopt step fails.
17419            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17420                    REASON_INSTALL,
17421                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17422                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17423            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17424                    null /* instructionSets */,
17425                    getOrCreateCompilerPackageStats(pkg),
17426                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17427                    dexoptOptions);
17428            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17429        }
17430
17431        // Notify BackgroundDexOptService that the package has been changed.
17432        // If this is an update of a package which used to fail to compile,
17433        // BackgroundDexOptService will remove it from its blacklist.
17434        // TODO: Layering violation
17435        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17436
17437        synchronized (mPackages) {
17438            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17439            if (ps != null) {
17440                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17441                ps.setUpdateAvailable(false /*updateAvailable*/);
17442            }
17443
17444            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17445            for (int i = 0; i < childCount; i++) {
17446                PackageParser.Package childPkg = pkg.childPackages.get(i);
17447                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17448                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17449                if (childPs != null) {
17450                    childRes.newUsers = childPs.queryInstalledUsers(
17451                            sUserManager.getUserIds(), true);
17452                }
17453            }
17454
17455            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17456                updateSequenceNumberLP(ps, res.newUsers);
17457                updateInstantAppInstallerLocked(pkgName);
17458            }
17459        }
17460    }
17461
17462    private void startIntentFilterVerifications(int userId, boolean replacing,
17463            PackageParser.Package pkg) {
17464        if (mIntentFilterVerifierComponent == null) {
17465            Slog.w(TAG, "No IntentFilter verification will not be done as "
17466                    + "there is no IntentFilterVerifier available!");
17467            return;
17468        }
17469
17470        final int verifierUid = getPackageUid(
17471                mIntentFilterVerifierComponent.getPackageName(),
17472                MATCH_DEBUG_TRIAGED_MISSING,
17473                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17474
17475        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17476        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17477        mHandler.sendMessage(msg);
17478
17479        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17480        for (int i = 0; i < childCount; i++) {
17481            PackageParser.Package childPkg = pkg.childPackages.get(i);
17482            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17483            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17484            mHandler.sendMessage(msg);
17485        }
17486    }
17487
17488    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17489            PackageParser.Package pkg) {
17490        int size = pkg.activities.size();
17491        if (size == 0) {
17492            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17493                    "No activity, so no need to verify any IntentFilter!");
17494            return;
17495        }
17496
17497        final boolean hasDomainURLs = hasDomainURLs(pkg);
17498        if (!hasDomainURLs) {
17499            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17500                    "No domain URLs, so no need to verify any IntentFilter!");
17501            return;
17502        }
17503
17504        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17505                + " if any IntentFilter from the " + size
17506                + " Activities needs verification ...");
17507
17508        int count = 0;
17509        final String packageName = pkg.packageName;
17510
17511        synchronized (mPackages) {
17512            // If this is a new install and we see that we've already run verification for this
17513            // package, we have nothing to do: it means the state was restored from backup.
17514            if (!replacing) {
17515                IntentFilterVerificationInfo ivi =
17516                        mSettings.getIntentFilterVerificationLPr(packageName);
17517                if (ivi != null) {
17518                    if (DEBUG_DOMAIN_VERIFICATION) {
17519                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17520                                + ivi.getStatusString());
17521                    }
17522                    return;
17523                }
17524            }
17525
17526            // If any filters need to be verified, then all need to be.
17527            boolean needToVerify = false;
17528            for (PackageParser.Activity a : pkg.activities) {
17529                for (ActivityIntentInfo filter : a.intents) {
17530                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17531                        if (DEBUG_DOMAIN_VERIFICATION) {
17532                            Slog.d(TAG,
17533                                    "Intent filter needs verification, so processing all filters");
17534                        }
17535                        needToVerify = true;
17536                        break;
17537                    }
17538                }
17539            }
17540
17541            if (needToVerify) {
17542                final int verificationId = mIntentFilterVerificationToken++;
17543                for (PackageParser.Activity a : pkg.activities) {
17544                    for (ActivityIntentInfo filter : a.intents) {
17545                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17546                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17547                                    "Verification needed for IntentFilter:" + filter.toString());
17548                            mIntentFilterVerifier.addOneIntentFilterVerification(
17549                                    verifierUid, userId, verificationId, filter, packageName);
17550                            count++;
17551                        }
17552                    }
17553                }
17554            }
17555        }
17556
17557        if (count > 0) {
17558            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17559                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17560                    +  " for userId:" + userId);
17561            mIntentFilterVerifier.startVerifications(userId);
17562        } else {
17563            if (DEBUG_DOMAIN_VERIFICATION) {
17564                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17565            }
17566        }
17567    }
17568
17569    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17570        final ComponentName cn  = filter.activity.getComponentName();
17571        final String packageName = cn.getPackageName();
17572
17573        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17574                packageName);
17575        if (ivi == null) {
17576            return true;
17577        }
17578        int status = ivi.getStatus();
17579        switch (status) {
17580            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17581            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17582                return true;
17583
17584            default:
17585                // Nothing to do
17586                return false;
17587        }
17588    }
17589
17590    private static boolean isMultiArch(ApplicationInfo info) {
17591        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17592    }
17593
17594    private static boolean isExternal(PackageParser.Package pkg) {
17595        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17596    }
17597
17598    private static boolean isExternal(PackageSetting ps) {
17599        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17600    }
17601
17602    private static boolean isSystemApp(PackageParser.Package pkg) {
17603        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17604    }
17605
17606    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17607        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17608    }
17609
17610    private static boolean isOemApp(PackageParser.Package pkg) {
17611        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17612    }
17613
17614    private static boolean isVendorApp(PackageParser.Package pkg) {
17615        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17616    }
17617
17618    private static boolean isProductApp(PackageParser.Package pkg) {
17619        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17620    }
17621
17622    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17623        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17624    }
17625
17626    private static boolean isSystemApp(PackageSetting ps) {
17627        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17628    }
17629
17630    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17631        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17632    }
17633
17634    private int packageFlagsToInstallFlags(PackageSetting ps) {
17635        int installFlags = 0;
17636        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17637            // This existing package was an external ASEC install when we have
17638            // the external flag without a UUID
17639            installFlags |= PackageManager.INSTALL_EXTERNAL;
17640        }
17641        if (ps.isForwardLocked()) {
17642            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17643        }
17644        return installFlags;
17645    }
17646
17647    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17648        if (isExternal(pkg)) {
17649            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17650                return mSettings.getExternalVersion();
17651            } else {
17652                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17653            }
17654        } else {
17655            return mSettings.getInternalVersion();
17656        }
17657    }
17658
17659    private void deleteTempPackageFiles() {
17660        final FilenameFilter filter = new FilenameFilter() {
17661            public boolean accept(File dir, String name) {
17662                return name.startsWith("vmdl") && name.endsWith(".tmp");
17663            }
17664        };
17665        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17666            file.delete();
17667        }
17668    }
17669
17670    @Override
17671    public void deletePackageAsUser(String packageName, int versionCode,
17672            IPackageDeleteObserver observer, int userId, int flags) {
17673        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17674                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17675    }
17676
17677    @Override
17678    public void deletePackageVersioned(VersionedPackage versionedPackage,
17679            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17680        final int callingUid = Binder.getCallingUid();
17681        mContext.enforceCallingOrSelfPermission(
17682                android.Manifest.permission.DELETE_PACKAGES, null);
17683        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17684        Preconditions.checkNotNull(versionedPackage);
17685        Preconditions.checkNotNull(observer);
17686        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17687                PackageManager.VERSION_CODE_HIGHEST,
17688                Long.MAX_VALUE, "versionCode must be >= -1");
17689
17690        final String packageName = versionedPackage.getPackageName();
17691        final long versionCode = versionedPackage.getLongVersionCode();
17692        final String internalPackageName;
17693        synchronized (mPackages) {
17694            // Normalize package name to handle renamed packages and static libs
17695            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17696        }
17697
17698        final int uid = Binder.getCallingUid();
17699        if (!isOrphaned(internalPackageName)
17700                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17701            try {
17702                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17703                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17704                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17705                observer.onUserActionRequired(intent);
17706            } catch (RemoteException re) {
17707            }
17708            return;
17709        }
17710        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17711        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17712        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17713            mContext.enforceCallingOrSelfPermission(
17714                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17715                    "deletePackage for user " + userId);
17716        }
17717
17718        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17719            try {
17720                observer.onPackageDeleted(packageName,
17721                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17722            } catch (RemoteException re) {
17723            }
17724            return;
17725        }
17726
17727        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17728            try {
17729                observer.onPackageDeleted(packageName,
17730                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17731            } catch (RemoteException re) {
17732            }
17733            return;
17734        }
17735
17736        if (DEBUG_REMOVE) {
17737            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17738                    + " deleteAllUsers: " + deleteAllUsers + " version="
17739                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17740                    ? "VERSION_CODE_HIGHEST" : versionCode));
17741        }
17742        // Queue up an async operation since the package deletion may take a little while.
17743        mHandler.post(new Runnable() {
17744            public void run() {
17745                mHandler.removeCallbacks(this);
17746                int returnCode;
17747                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17748                boolean doDeletePackage = true;
17749                if (ps != null) {
17750                    final boolean targetIsInstantApp =
17751                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17752                    doDeletePackage = !targetIsInstantApp
17753                            || canViewInstantApps;
17754                }
17755                if (doDeletePackage) {
17756                    if (!deleteAllUsers) {
17757                        returnCode = deletePackageX(internalPackageName, versionCode,
17758                                userId, deleteFlags);
17759                    } else {
17760                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17761                                internalPackageName, users);
17762                        // If nobody is blocking uninstall, proceed with delete for all users
17763                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17764                            returnCode = deletePackageX(internalPackageName, versionCode,
17765                                    userId, deleteFlags);
17766                        } else {
17767                            // Otherwise uninstall individually for users with blockUninstalls=false
17768                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17769                            for (int userId : users) {
17770                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17771                                    returnCode = deletePackageX(internalPackageName, versionCode,
17772                                            userId, userFlags);
17773                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17774                                        Slog.w(TAG, "Package delete failed for user " + userId
17775                                                + ", returnCode " + returnCode);
17776                                    }
17777                                }
17778                            }
17779                            // The app has only been marked uninstalled for certain users.
17780                            // We still need to report that delete was blocked
17781                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17782                        }
17783                    }
17784                } else {
17785                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17786                }
17787                try {
17788                    observer.onPackageDeleted(packageName, returnCode, null);
17789                } catch (RemoteException e) {
17790                    Log.i(TAG, "Observer no longer exists.");
17791                } //end catch
17792            } //end run
17793        });
17794    }
17795
17796    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17797        if (pkg.staticSharedLibName != null) {
17798            return pkg.manifestPackageName;
17799        }
17800        return pkg.packageName;
17801    }
17802
17803    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17804        // Handle renamed packages
17805        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17806        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17807
17808        // Is this a static library?
17809        LongSparseArray<SharedLibraryEntry> versionedLib =
17810                mStaticLibsByDeclaringPackage.get(packageName);
17811        if (versionedLib == null || versionedLib.size() <= 0) {
17812            return packageName;
17813        }
17814
17815        // Figure out which lib versions the caller can see
17816        LongSparseLongArray versionsCallerCanSee = null;
17817        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17818        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17819                && callingAppId != Process.ROOT_UID) {
17820            versionsCallerCanSee = new LongSparseLongArray();
17821            String libName = versionedLib.valueAt(0).info.getName();
17822            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17823            if (uidPackages != null) {
17824                for (String uidPackage : uidPackages) {
17825                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17826                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17827                    if (libIdx >= 0) {
17828                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17829                        versionsCallerCanSee.append(libVersion, libVersion);
17830                    }
17831                }
17832            }
17833        }
17834
17835        // Caller can see nothing - done
17836        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17837            return packageName;
17838        }
17839
17840        // Find the version the caller can see and the app version code
17841        SharedLibraryEntry highestVersion = null;
17842        final int versionCount = versionedLib.size();
17843        for (int i = 0; i < versionCount; i++) {
17844            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17845            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17846                    libEntry.info.getLongVersion()) < 0) {
17847                continue;
17848            }
17849            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17850            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17851                if (libVersionCode == versionCode) {
17852                    return libEntry.apk;
17853                }
17854            } else if (highestVersion == null) {
17855                highestVersion = libEntry;
17856            } else if (libVersionCode  > highestVersion.info
17857                    .getDeclaringPackage().getLongVersionCode()) {
17858                highestVersion = libEntry;
17859            }
17860        }
17861
17862        if (highestVersion != null) {
17863            return highestVersion.apk;
17864        }
17865
17866        return packageName;
17867    }
17868
17869    boolean isCallerVerifier(int callingUid) {
17870        final int callingUserId = UserHandle.getUserId(callingUid);
17871        return mRequiredVerifierPackage != null &&
17872                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17873    }
17874
17875    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17876        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17877              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17878            return true;
17879        }
17880        final int callingUserId = UserHandle.getUserId(callingUid);
17881        // If the caller installed the pkgName, then allow it to silently uninstall.
17882        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17883            return true;
17884        }
17885
17886        // Allow package verifier to silently uninstall.
17887        if (mRequiredVerifierPackage != null &&
17888                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17889            return true;
17890        }
17891
17892        // Allow package uninstaller to silently uninstall.
17893        if (mRequiredUninstallerPackage != null &&
17894                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17895            return true;
17896        }
17897
17898        // Allow storage manager to silently uninstall.
17899        if (mStorageManagerPackage != null &&
17900                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17901            return true;
17902        }
17903
17904        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17905        // uninstall for device owner provisioning.
17906        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17907                == PERMISSION_GRANTED) {
17908            return true;
17909        }
17910
17911        return false;
17912    }
17913
17914    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17915        int[] result = EMPTY_INT_ARRAY;
17916        for (int userId : userIds) {
17917            if (getBlockUninstallForUser(packageName, userId)) {
17918                result = ArrayUtils.appendInt(result, userId);
17919            }
17920        }
17921        return result;
17922    }
17923
17924    @Override
17925    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17926        final int callingUid = Binder.getCallingUid();
17927        if (getInstantAppPackageName(callingUid) != null
17928                && !isCallerSameApp(packageName, callingUid)) {
17929            return false;
17930        }
17931        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17932    }
17933
17934    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17935        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17936                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17937        try {
17938            if (dpm != null) {
17939                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17940                        /* callingUserOnly =*/ false);
17941                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17942                        : deviceOwnerComponentName.getPackageName();
17943                // Does the package contains the device owner?
17944                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17945                // this check is probably not needed, since DO should be registered as a device
17946                // admin on some user too. (Original bug for this: b/17657954)
17947                if (packageName.equals(deviceOwnerPackageName)) {
17948                    return true;
17949                }
17950                // Does it contain a device admin for any user?
17951                int[] users;
17952                if (userId == UserHandle.USER_ALL) {
17953                    users = sUserManager.getUserIds();
17954                } else {
17955                    users = new int[]{userId};
17956                }
17957                for (int i = 0; i < users.length; ++i) {
17958                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17959                        return true;
17960                    }
17961                }
17962            }
17963        } catch (RemoteException e) {
17964        }
17965        return false;
17966    }
17967
17968    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17969        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17970    }
17971
17972    /**
17973     *  This method is an internal method that could be get invoked either
17974     *  to delete an installed package or to clean up a failed installation.
17975     *  After deleting an installed package, a broadcast is sent to notify any
17976     *  listeners that the package has been removed. For cleaning up a failed
17977     *  installation, the broadcast is not necessary since the package's
17978     *  installation wouldn't have sent the initial broadcast either
17979     *  The key steps in deleting a package are
17980     *  deleting the package information in internal structures like mPackages,
17981     *  deleting the packages base directories through installd
17982     *  updating mSettings to reflect current status
17983     *  persisting settings for later use
17984     *  sending a broadcast if necessary
17985     */
17986    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17987        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17988        final boolean res;
17989
17990        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17991                ? UserHandle.USER_ALL : userId;
17992
17993        if (isPackageDeviceAdmin(packageName, removeUser)) {
17994            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17995            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17996        }
17997
17998        PackageSetting uninstalledPs = null;
17999        PackageParser.Package pkg = null;
18000
18001        // for the uninstall-updates case and restricted profiles, remember the per-
18002        // user handle installed state
18003        int[] allUsers;
18004        synchronized (mPackages) {
18005            uninstalledPs = mSettings.mPackages.get(packageName);
18006            if (uninstalledPs == null) {
18007                Slog.w(TAG, "Not removing non-existent package " + packageName);
18008                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18009            }
18010
18011            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18012                    && uninstalledPs.versionCode != versionCode) {
18013                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18014                        + uninstalledPs.versionCode + " != " + versionCode);
18015                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18016            }
18017
18018            // Static shared libs can be declared by any package, so let us not
18019            // allow removing a package if it provides a lib others depend on.
18020            pkg = mPackages.get(packageName);
18021
18022            allUsers = sUserManager.getUserIds();
18023
18024            if (pkg != null && pkg.staticSharedLibName != null) {
18025                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18026                        pkg.staticSharedLibVersion);
18027                if (libEntry != null) {
18028                    for (int currUserId : allUsers) {
18029                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18030                            continue;
18031                        }
18032                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18033                                libEntry.info, 0, currUserId);
18034                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18035                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18036                                    + " hosting lib " + libEntry.info.getName() + " version "
18037                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
18038                                    + " for user " + currUserId);
18039                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18040                        }
18041                    }
18042                }
18043            }
18044
18045            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18046        }
18047
18048        final int freezeUser;
18049        if (isUpdatedSystemApp(uninstalledPs)
18050                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18051            // We're downgrading a system app, which will apply to all users, so
18052            // freeze them all during the downgrade
18053            freezeUser = UserHandle.USER_ALL;
18054        } else {
18055            freezeUser = removeUser;
18056        }
18057
18058        synchronized (mInstallLock) {
18059            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18060            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18061                    deleteFlags, "deletePackageX")) {
18062                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18063                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18064            }
18065            synchronized (mPackages) {
18066                if (res) {
18067                    if (pkg != null) {
18068                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18069                    }
18070                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18071                    updateInstantAppInstallerLocked(packageName);
18072                }
18073            }
18074        }
18075
18076        if (res) {
18077            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18078            info.sendPackageRemovedBroadcasts(killApp);
18079            info.sendSystemPackageUpdatedBroadcasts();
18080            info.sendSystemPackageAppearedBroadcasts();
18081        }
18082        // Force a gc here.
18083        Runtime.getRuntime().gc();
18084        // Delete the resources here after sending the broadcast to let
18085        // other processes clean up before deleting resources.
18086        if (info.args != null) {
18087            synchronized (mInstallLock) {
18088                info.args.doPostDeleteLI(true);
18089            }
18090        }
18091
18092        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18093    }
18094
18095    static class PackageRemovedInfo {
18096        final PackageSender packageSender;
18097        String removedPackage;
18098        String installerPackageName;
18099        int uid = -1;
18100        int removedAppId = -1;
18101        int[] origUsers;
18102        int[] removedUsers = null;
18103        int[] broadcastUsers = null;
18104        int[] instantUserIds = null;
18105        SparseArray<Integer> installReasons;
18106        boolean isRemovedPackageSystemUpdate = false;
18107        boolean isUpdate;
18108        boolean dataRemoved;
18109        boolean removedForAllUsers;
18110        boolean isStaticSharedLib;
18111        // Clean up resources deleted packages.
18112        InstallArgs args = null;
18113        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18114        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18115
18116        PackageRemovedInfo(PackageSender packageSender) {
18117            this.packageSender = packageSender;
18118        }
18119
18120        void sendPackageRemovedBroadcasts(boolean killApp) {
18121            sendPackageRemovedBroadcastInternal(killApp);
18122            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18123            for (int i = 0; i < childCount; i++) {
18124                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18125                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18126            }
18127        }
18128
18129        void sendSystemPackageUpdatedBroadcasts() {
18130            if (isRemovedPackageSystemUpdate) {
18131                sendSystemPackageUpdatedBroadcastsInternal();
18132                final int childCount = (removedChildPackages != null)
18133                        ? removedChildPackages.size() : 0;
18134                for (int i = 0; i < childCount; i++) {
18135                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18136                    if (childInfo.isRemovedPackageSystemUpdate) {
18137                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18138                    }
18139                }
18140            }
18141        }
18142
18143        void sendSystemPackageAppearedBroadcasts() {
18144            final int packageCount = (appearedChildPackages != null)
18145                    ? appearedChildPackages.size() : 0;
18146            for (int i = 0; i < packageCount; i++) {
18147                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18148                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18149                    true /*sendBootCompleted*/, false /*startReceiver*/,
18150                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18151            }
18152        }
18153
18154        private void sendSystemPackageUpdatedBroadcastsInternal() {
18155            Bundle extras = new Bundle(2);
18156            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18157            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18158            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18159                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18160            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18161                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18162            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18163                null, null, 0, removedPackage, null, null, null);
18164            if (installerPackageName != null) {
18165                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18166                        removedPackage, extras, 0 /*flags*/,
18167                        installerPackageName, null, null, null);
18168                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18169                        removedPackage, extras, 0 /*flags*/,
18170                        installerPackageName, null, null, null);
18171            }
18172        }
18173
18174        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18175            // Don't send static shared library removal broadcasts as these
18176            // libs are visible only the the apps that depend on them an one
18177            // cannot remove the library if it has a dependency.
18178            if (isStaticSharedLib) {
18179                return;
18180            }
18181            Bundle extras = new Bundle(2);
18182            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18183            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18184            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18185            if (isUpdate || isRemovedPackageSystemUpdate) {
18186                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18187            }
18188            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18189            if (removedPackage != null) {
18190                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18191                    removedPackage, extras, 0, null /*targetPackage*/, null,
18192                    broadcastUsers, instantUserIds);
18193                if (installerPackageName != null) {
18194                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18195                            removedPackage, extras, 0 /*flags*/,
18196                            installerPackageName, null, broadcastUsers, instantUserIds);
18197                }
18198                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18199                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18200                        removedPackage, extras,
18201                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18202                        null, null, broadcastUsers, instantUserIds);
18203                    packageSender.notifyPackageRemoved(removedPackage);
18204                }
18205            }
18206            if (removedAppId >= 0) {
18207                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18208                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18209                    null, null, broadcastUsers, instantUserIds);
18210            }
18211        }
18212
18213        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18214            removedUsers = userIds;
18215            if (removedUsers == null) {
18216                broadcastUsers = null;
18217                return;
18218            }
18219
18220            broadcastUsers = EMPTY_INT_ARRAY;
18221            instantUserIds = EMPTY_INT_ARRAY;
18222            for (int i = userIds.length - 1; i >= 0; --i) {
18223                final int userId = userIds[i];
18224                if (deletedPackageSetting.getInstantApp(userId)) {
18225                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18226                } else {
18227                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18228                }
18229            }
18230        }
18231    }
18232
18233    /*
18234     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18235     * flag is not set, the data directory is removed as well.
18236     * make sure this flag is set for partially installed apps. If not its meaningless to
18237     * delete a partially installed application.
18238     */
18239    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18240            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18241        String packageName = ps.name;
18242        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18243        // Retrieve object to delete permissions for shared user later on
18244        final PackageParser.Package deletedPkg;
18245        final PackageSetting deletedPs;
18246        // reader
18247        synchronized (mPackages) {
18248            deletedPkg = mPackages.get(packageName);
18249            deletedPs = mSettings.mPackages.get(packageName);
18250            if (outInfo != null) {
18251                outInfo.removedPackage = packageName;
18252                outInfo.installerPackageName = ps.installerPackageName;
18253                outInfo.isStaticSharedLib = deletedPkg != null
18254                        && deletedPkg.staticSharedLibName != null;
18255                outInfo.populateUsers(deletedPs == null ? null
18256                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18257            }
18258        }
18259
18260        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18261
18262        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18263            final PackageParser.Package resolvedPkg;
18264            if (deletedPkg != null) {
18265                resolvedPkg = deletedPkg;
18266            } else {
18267                // We don't have a parsed package when it lives on an ejected
18268                // adopted storage device, so fake something together
18269                resolvedPkg = new PackageParser.Package(ps.name);
18270                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18271            }
18272            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18273                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18274            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18275            if (outInfo != null) {
18276                outInfo.dataRemoved = true;
18277            }
18278            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18279        }
18280
18281        int removedAppId = -1;
18282
18283        // writer
18284        synchronized (mPackages) {
18285            boolean installedStateChanged = false;
18286            if (deletedPs != null) {
18287                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18288                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18289                    clearDefaultBrowserIfNeeded(packageName);
18290                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18291                    removedAppId = mSettings.removePackageLPw(packageName);
18292                    if (outInfo != null) {
18293                        outInfo.removedAppId = removedAppId;
18294                    }
18295                    mPermissionManager.updatePermissions(
18296                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18297                    if (deletedPs.sharedUser != null) {
18298                        // Remove permissions associated with package. Since runtime
18299                        // permissions are per user we have to kill the removed package
18300                        // or packages running under the shared user of the removed
18301                        // package if revoking the permissions requested only by the removed
18302                        // package is successful and this causes a change in gids.
18303                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18304                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18305                                    userId);
18306                            if (userIdToKill == UserHandle.USER_ALL
18307                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18308                                // If gids changed for this user, kill all affected packages.
18309                                mHandler.post(new Runnable() {
18310                                    @Override
18311                                    public void run() {
18312                                        // This has to happen with no lock held.
18313                                        killApplication(deletedPs.name, deletedPs.appId,
18314                                                KILL_APP_REASON_GIDS_CHANGED);
18315                                    }
18316                                });
18317                                break;
18318                            }
18319                        }
18320                    }
18321                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18322                }
18323                // make sure to preserve per-user disabled state if this removal was just
18324                // a downgrade of a system app to the factory package
18325                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18326                    if (DEBUG_REMOVE) {
18327                        Slog.d(TAG, "Propagating install state across downgrade");
18328                    }
18329                    for (int userId : allUserHandles) {
18330                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18331                        if (DEBUG_REMOVE) {
18332                            Slog.d(TAG, "    user " + userId + " => " + installed);
18333                        }
18334                        if (installed != ps.getInstalled(userId)) {
18335                            installedStateChanged = true;
18336                        }
18337                        ps.setInstalled(installed, userId);
18338                    }
18339                }
18340            }
18341            // can downgrade to reader
18342            if (writeSettings) {
18343                // Save settings now
18344                mSettings.writeLPr();
18345            }
18346            if (installedStateChanged) {
18347                mSettings.writeKernelMappingLPr(ps);
18348            }
18349        }
18350        if (removedAppId != -1) {
18351            // A user ID was deleted here. Go through all users and remove it
18352            // from KeyStore.
18353            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18354        }
18355    }
18356
18357    static boolean locationIsPrivileged(String path) {
18358        try {
18359            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18360            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18361            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18362            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18363            return path.startsWith(privilegedAppDir.getCanonicalPath())
18364                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18365                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18366                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18367        } catch (IOException e) {
18368            Slog.e(TAG, "Unable to access code path " + path);
18369        }
18370        return false;
18371    }
18372
18373    static boolean locationIsOem(String path) {
18374        try {
18375            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18376        } catch (IOException e) {
18377            Slog.e(TAG, "Unable to access code path " + path);
18378        }
18379        return false;
18380    }
18381
18382    static boolean locationIsVendor(String path) {
18383        try {
18384            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18385                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18386        } catch (IOException e) {
18387            Slog.e(TAG, "Unable to access code path " + path);
18388        }
18389        return false;
18390    }
18391
18392    static boolean locationIsProduct(String path) {
18393        try {
18394            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18395        } catch (IOException e) {
18396            Slog.e(TAG, "Unable to access code path " + path);
18397        }
18398        return false;
18399    }
18400
18401    /*
18402     * Tries to delete system package.
18403     */
18404    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18405            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18406            boolean writeSettings) {
18407        if (deletedPs.parentPackageName != null) {
18408            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18409            return false;
18410        }
18411
18412        final boolean applyUserRestrictions
18413                = (allUserHandles != null) && (outInfo.origUsers != null);
18414        final PackageSetting disabledPs;
18415        // Confirm if the system package has been updated
18416        // An updated system app can be deleted. This will also have to restore
18417        // the system pkg from system partition
18418        // reader
18419        synchronized (mPackages) {
18420            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18421        }
18422
18423        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18424                + " disabledPs=" + disabledPs);
18425
18426        if (disabledPs == null) {
18427            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18428            return false;
18429        } else if (DEBUG_REMOVE) {
18430            Slog.d(TAG, "Deleting system pkg from data partition");
18431        }
18432
18433        if (DEBUG_REMOVE) {
18434            if (applyUserRestrictions) {
18435                Slog.d(TAG, "Remembering install states:");
18436                for (int userId : allUserHandles) {
18437                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18438                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18439                }
18440            }
18441        }
18442
18443        // Delete the updated package
18444        outInfo.isRemovedPackageSystemUpdate = true;
18445        if (outInfo.removedChildPackages != null) {
18446            final int childCount = (deletedPs.childPackageNames != null)
18447                    ? deletedPs.childPackageNames.size() : 0;
18448            for (int i = 0; i < childCount; i++) {
18449                String childPackageName = deletedPs.childPackageNames.get(i);
18450                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18451                        .contains(childPackageName)) {
18452                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18453                            childPackageName);
18454                    if (childInfo != null) {
18455                        childInfo.isRemovedPackageSystemUpdate = true;
18456                    }
18457                }
18458            }
18459        }
18460
18461        if (disabledPs.versionCode < deletedPs.versionCode) {
18462            // Delete data for downgrades
18463            flags &= ~PackageManager.DELETE_KEEP_DATA;
18464        } else {
18465            // Preserve data by setting flag
18466            flags |= PackageManager.DELETE_KEEP_DATA;
18467        }
18468
18469        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18470                outInfo, writeSettings, disabledPs.pkg);
18471        if (!ret) {
18472            return false;
18473        }
18474
18475        // writer
18476        synchronized (mPackages) {
18477            // NOTE: The system package always needs to be enabled; even if it's for
18478            // a compressed stub. If we don't, installing the system package fails
18479            // during scan [scanning checks the disabled packages]. We will reverse
18480            // this later, after we've "installed" the stub.
18481            // Reinstate the old system package
18482            enableSystemPackageLPw(disabledPs.pkg);
18483            // Remove any native libraries from the upgraded package.
18484            removeNativeBinariesLI(deletedPs);
18485        }
18486
18487        // Install the system package
18488        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18489        try {
18490            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18491                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18492        } catch (PackageManagerException e) {
18493            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18494                    + e.getMessage());
18495            return false;
18496        } finally {
18497            if (disabledPs.pkg.isStub) {
18498                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18499            }
18500        }
18501        return true;
18502    }
18503
18504    /**
18505     * Installs a package that's already on the system partition.
18506     */
18507    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18508            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18509            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18510                    throws PackageManagerException {
18511        @ParseFlags int parseFlags =
18512                mDefParseFlags
18513                | PackageParser.PARSE_MUST_BE_APK
18514                | PackageParser.PARSE_IS_SYSTEM_DIR;
18515        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18516        if (isPrivileged || locationIsPrivileged(codePathString)) {
18517            scanFlags |= SCAN_AS_PRIVILEGED;
18518        }
18519        if (locationIsOem(codePathString)) {
18520            scanFlags |= SCAN_AS_OEM;
18521        }
18522        if (locationIsVendor(codePathString)) {
18523            scanFlags |= SCAN_AS_VENDOR;
18524        }
18525        if (locationIsProduct(codePathString)) {
18526            scanFlags |= SCAN_AS_PRODUCT;
18527        }
18528
18529        final File codePath = new File(codePathString);
18530        final PackageParser.Package pkg =
18531                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18532
18533        try {
18534            // update shared libraries for the newly re-installed system package
18535            updateSharedLibrariesLPr(pkg, null);
18536        } catch (PackageManagerException e) {
18537            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18538        }
18539
18540        prepareAppDataAfterInstallLIF(pkg);
18541
18542        // writer
18543        synchronized (mPackages) {
18544            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18545
18546            // Propagate the permissions state as we do not want to drop on the floor
18547            // runtime permissions. The update permissions method below will take
18548            // care of removing obsolete permissions and grant install permissions.
18549            if (origPermissionState != null) {
18550                ps.getPermissionsState().copyFrom(origPermissionState);
18551            }
18552            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18553                    mPermissionCallback);
18554
18555            final boolean applyUserRestrictions
18556                    = (allUserHandles != null) && (origUserHandles != null);
18557            if (applyUserRestrictions) {
18558                boolean installedStateChanged = false;
18559                if (DEBUG_REMOVE) {
18560                    Slog.d(TAG, "Propagating install state across reinstall");
18561                }
18562                for (int userId : allUserHandles) {
18563                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18564                    if (DEBUG_REMOVE) {
18565                        Slog.d(TAG, "    user " + userId + " => " + installed);
18566                    }
18567                    if (installed != ps.getInstalled(userId)) {
18568                        installedStateChanged = true;
18569                    }
18570                    ps.setInstalled(installed, userId);
18571
18572                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18573                }
18574                // Regardless of writeSettings we need to ensure that this restriction
18575                // state propagation is persisted
18576                mSettings.writeAllUsersPackageRestrictionsLPr();
18577                if (installedStateChanged) {
18578                    mSettings.writeKernelMappingLPr(ps);
18579                }
18580            }
18581            // can downgrade to reader here
18582            if (writeSettings) {
18583                mSettings.writeLPr();
18584            }
18585        }
18586        return pkg;
18587    }
18588
18589    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18590            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18591            PackageRemovedInfo outInfo, boolean writeSettings,
18592            PackageParser.Package replacingPackage) {
18593        synchronized (mPackages) {
18594            if (outInfo != null) {
18595                outInfo.uid = ps.appId;
18596            }
18597
18598            if (outInfo != null && outInfo.removedChildPackages != null) {
18599                final int childCount = (ps.childPackageNames != null)
18600                        ? ps.childPackageNames.size() : 0;
18601                for (int i = 0; i < childCount; i++) {
18602                    String childPackageName = ps.childPackageNames.get(i);
18603                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18604                    if (childPs == null) {
18605                        return false;
18606                    }
18607                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18608                            childPackageName);
18609                    if (childInfo != null) {
18610                        childInfo.uid = childPs.appId;
18611                    }
18612                }
18613            }
18614        }
18615
18616        // Delete package data from internal structures and also remove data if flag is set
18617        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18618
18619        // Delete the child packages data
18620        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18621        for (int i = 0; i < childCount; i++) {
18622            PackageSetting childPs;
18623            synchronized (mPackages) {
18624                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18625            }
18626            if (childPs != null) {
18627                PackageRemovedInfo childOutInfo = (outInfo != null
18628                        && outInfo.removedChildPackages != null)
18629                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18630                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18631                        && (replacingPackage != null
18632                        && !replacingPackage.hasChildPackage(childPs.name))
18633                        ? flags & ~DELETE_KEEP_DATA : flags;
18634                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18635                        deleteFlags, writeSettings);
18636            }
18637        }
18638
18639        // Delete application code and resources only for parent packages
18640        if (ps.parentPackageName == null) {
18641            if (deleteCodeAndResources && (outInfo != null)) {
18642                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18643                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18644                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18645            }
18646        }
18647
18648        return true;
18649    }
18650
18651    @Override
18652    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18653            int userId) {
18654        mContext.enforceCallingOrSelfPermission(
18655                android.Manifest.permission.DELETE_PACKAGES, null);
18656        synchronized (mPackages) {
18657            // Cannot block uninstall of static shared libs as they are
18658            // considered a part of the using app (emulating static linking).
18659            // Also static libs are installed always on internal storage.
18660            PackageParser.Package pkg = mPackages.get(packageName);
18661            if (pkg != null && pkg.staticSharedLibName != null) {
18662                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18663                        + " providing static shared library: " + pkg.staticSharedLibName);
18664                return false;
18665            }
18666            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18667            mSettings.writePackageRestrictionsLPr(userId);
18668        }
18669        return true;
18670    }
18671
18672    @Override
18673    public boolean getBlockUninstallForUser(String packageName, int userId) {
18674        synchronized (mPackages) {
18675            final PackageSetting ps = mSettings.mPackages.get(packageName);
18676            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18677                return false;
18678            }
18679            return mSettings.getBlockUninstallLPr(userId, packageName);
18680        }
18681    }
18682
18683    @Override
18684    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18685        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18686        synchronized (mPackages) {
18687            PackageSetting ps = mSettings.mPackages.get(packageName);
18688            if (ps == null) {
18689                Log.w(TAG, "Package doesn't exist: " + packageName);
18690                return false;
18691            }
18692            if (systemUserApp) {
18693                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18694            } else {
18695                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18696            }
18697            mSettings.writeLPr();
18698        }
18699        return true;
18700    }
18701
18702    /*
18703     * This method handles package deletion in general
18704     */
18705    private boolean deletePackageLIF(String packageName, UserHandle user,
18706            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18707            PackageRemovedInfo outInfo, boolean writeSettings,
18708            PackageParser.Package replacingPackage) {
18709        if (packageName == null) {
18710            Slog.w(TAG, "Attempt to delete null packageName.");
18711            return false;
18712        }
18713
18714        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18715
18716        PackageSetting ps;
18717        synchronized (mPackages) {
18718            ps = mSettings.mPackages.get(packageName);
18719            if (ps == null) {
18720                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18721                return false;
18722            }
18723
18724            if (ps.parentPackageName != null && (!isSystemApp(ps)
18725                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18726                if (DEBUG_REMOVE) {
18727                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18728                            + ((user == null) ? UserHandle.USER_ALL : user));
18729                }
18730                final int removedUserId = (user != null) ? user.getIdentifier()
18731                        : UserHandle.USER_ALL;
18732
18733                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18734                    return false;
18735                }
18736                markPackageUninstalledForUserLPw(ps, user);
18737                scheduleWritePackageRestrictionsLocked(user);
18738                return true;
18739            }
18740        }
18741
18742        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
18743        if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
18744            onSuspendingPackageRemoved(packageName, userId);
18745        }
18746
18747
18748        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18749                && user.getIdentifier() != UserHandle.USER_ALL)) {
18750            // The caller is asking that the package only be deleted for a single
18751            // user.  To do this, we just mark its uninstalled state and delete
18752            // its data. If this is a system app, we only allow this to happen if
18753            // they have set the special DELETE_SYSTEM_APP which requests different
18754            // semantics than normal for uninstalling system apps.
18755            markPackageUninstalledForUserLPw(ps, user);
18756
18757            if (!isSystemApp(ps)) {
18758                // Do not uninstall the APK if an app should be cached
18759                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18760                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18761                    // Other user still have this package installed, so all
18762                    // we need to do is clear this user's data and save that
18763                    // it is uninstalled.
18764                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18765                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18766                        return false;
18767                    }
18768                    scheduleWritePackageRestrictionsLocked(user);
18769                    return true;
18770                } else {
18771                    // We need to set it back to 'installed' so the uninstall
18772                    // broadcasts will be sent correctly.
18773                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18774                    ps.setInstalled(true, user.getIdentifier());
18775                    mSettings.writeKernelMappingLPr(ps);
18776                }
18777            } else {
18778                // This is a system app, so we assume that the
18779                // other users still have this package installed, so all
18780                // we need to do is clear this user's data and save that
18781                // it is uninstalled.
18782                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18783                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18784                    return false;
18785                }
18786                scheduleWritePackageRestrictionsLocked(user);
18787                return true;
18788            }
18789        }
18790
18791        // If we are deleting a composite package for all users, keep track
18792        // of result for each child.
18793        if (ps.childPackageNames != null && outInfo != null) {
18794            synchronized (mPackages) {
18795                final int childCount = ps.childPackageNames.size();
18796                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18797                for (int i = 0; i < childCount; i++) {
18798                    String childPackageName = ps.childPackageNames.get(i);
18799                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18800                    childInfo.removedPackage = childPackageName;
18801                    childInfo.installerPackageName = ps.installerPackageName;
18802                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18803                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18804                    if (childPs != null) {
18805                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18806                    }
18807                }
18808            }
18809        }
18810
18811        boolean ret = false;
18812        if (isSystemApp(ps)) {
18813            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18814            // When an updated system application is deleted we delete the existing resources
18815            // as well and fall back to existing code in system partition
18816            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18817        } else {
18818            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18819            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18820                    outInfo, writeSettings, replacingPackage);
18821        }
18822
18823        // Take a note whether we deleted the package for all users
18824        if (outInfo != null) {
18825            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18826            if (outInfo.removedChildPackages != null) {
18827                synchronized (mPackages) {
18828                    final int childCount = outInfo.removedChildPackages.size();
18829                    for (int i = 0; i < childCount; i++) {
18830                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18831                        if (childInfo != null) {
18832                            childInfo.removedForAllUsers = mPackages.get(
18833                                    childInfo.removedPackage) == null;
18834                        }
18835                    }
18836                }
18837            }
18838            // If we uninstalled an update to a system app there may be some
18839            // child packages that appeared as they are declared in the system
18840            // app but were not declared in the update.
18841            if (isSystemApp(ps)) {
18842                synchronized (mPackages) {
18843                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18844                    final int childCount = (updatedPs.childPackageNames != null)
18845                            ? updatedPs.childPackageNames.size() : 0;
18846                    for (int i = 0; i < childCount; i++) {
18847                        String childPackageName = updatedPs.childPackageNames.get(i);
18848                        if (outInfo.removedChildPackages == null
18849                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18850                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18851                            if (childPs == null) {
18852                                continue;
18853                            }
18854                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18855                            installRes.name = childPackageName;
18856                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18857                            installRes.pkg = mPackages.get(childPackageName);
18858                            installRes.uid = childPs.pkg.applicationInfo.uid;
18859                            if (outInfo.appearedChildPackages == null) {
18860                                outInfo.appearedChildPackages = new ArrayMap<>();
18861                            }
18862                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18863                        }
18864                    }
18865                }
18866            }
18867        }
18868
18869        return ret;
18870    }
18871
18872    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18873        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18874                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18875        for (int nextUserId : userIds) {
18876            if (DEBUG_REMOVE) {
18877                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18878            }
18879            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18880                    false /*installed*/,
18881                    true /*stopped*/,
18882                    true /*notLaunched*/,
18883                    false /*hidden*/,
18884                    false /*suspended*/,
18885                    null, /*suspendingPackage*/
18886                    null, /*suspendedAppExtras*/
18887                    null, /*suspendedLauncherExtras*/
18888                    false /*instantApp*/,
18889                    false /*virtualPreload*/,
18890                    null /*lastDisableAppCaller*/,
18891                    null /*enabledComponents*/,
18892                    null /*disabledComponents*/,
18893                    ps.readUserState(nextUserId).domainVerificationStatus,
18894                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18895                    null /*harmfulAppWarning*/);
18896        }
18897        mSettings.writeKernelMappingLPr(ps);
18898    }
18899
18900    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18901            PackageRemovedInfo outInfo) {
18902        final PackageParser.Package pkg;
18903        synchronized (mPackages) {
18904            pkg = mPackages.get(ps.name);
18905        }
18906
18907        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18908                : new int[] {userId};
18909        for (int nextUserId : userIds) {
18910            if (DEBUG_REMOVE) {
18911                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18912                        + nextUserId);
18913            }
18914
18915            destroyAppDataLIF(pkg, userId,
18916                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18917            destroyAppProfilesLIF(pkg, userId);
18918            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18919            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18920            schedulePackageCleaning(ps.name, nextUserId, false);
18921            synchronized (mPackages) {
18922                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18923                    scheduleWritePackageRestrictionsLocked(nextUserId);
18924                }
18925                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18926            }
18927        }
18928
18929        if (outInfo != null) {
18930            outInfo.removedPackage = ps.name;
18931            outInfo.installerPackageName = ps.installerPackageName;
18932            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18933            outInfo.removedAppId = ps.appId;
18934            outInfo.removedUsers = userIds;
18935            outInfo.broadcastUsers = userIds;
18936        }
18937
18938        return true;
18939    }
18940
18941    private final class ClearStorageConnection implements ServiceConnection {
18942        IMediaContainerService mContainerService;
18943
18944        @Override
18945        public void onServiceConnected(ComponentName name, IBinder service) {
18946            synchronized (this) {
18947                mContainerService = IMediaContainerService.Stub
18948                        .asInterface(Binder.allowBlocking(service));
18949                notifyAll();
18950            }
18951        }
18952
18953        @Override
18954        public void onServiceDisconnected(ComponentName name) {
18955        }
18956    }
18957
18958    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18959        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18960
18961        final boolean mounted;
18962        if (Environment.isExternalStorageEmulated()) {
18963            mounted = true;
18964        } else {
18965            final String status = Environment.getExternalStorageState();
18966
18967            mounted = status.equals(Environment.MEDIA_MOUNTED)
18968                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18969        }
18970
18971        if (!mounted) {
18972            return;
18973        }
18974
18975        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18976        int[] users;
18977        if (userId == UserHandle.USER_ALL) {
18978            users = sUserManager.getUserIds();
18979        } else {
18980            users = new int[] { userId };
18981        }
18982        final ClearStorageConnection conn = new ClearStorageConnection();
18983        if (mContext.bindServiceAsUser(
18984                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18985            try {
18986                for (int curUser : users) {
18987                    long timeout = SystemClock.uptimeMillis() + 5000;
18988                    synchronized (conn) {
18989                        long now;
18990                        while (conn.mContainerService == null &&
18991                                (now = SystemClock.uptimeMillis()) < timeout) {
18992                            try {
18993                                conn.wait(timeout - now);
18994                            } catch (InterruptedException e) {
18995                            }
18996                        }
18997                    }
18998                    if (conn.mContainerService == null) {
18999                        return;
19000                    }
19001
19002                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19003                    clearDirectory(conn.mContainerService,
19004                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19005                    if (allData) {
19006                        clearDirectory(conn.mContainerService,
19007                                userEnv.buildExternalStorageAppDataDirs(packageName));
19008                        clearDirectory(conn.mContainerService,
19009                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19010                    }
19011                }
19012            } finally {
19013                mContext.unbindService(conn);
19014            }
19015        }
19016    }
19017
19018    @Override
19019    public void clearApplicationProfileData(String packageName) {
19020        enforceSystemOrRoot("Only the system can clear all profile data");
19021
19022        final PackageParser.Package pkg;
19023        synchronized (mPackages) {
19024            pkg = mPackages.get(packageName);
19025        }
19026
19027        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19028            synchronized (mInstallLock) {
19029                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19030            }
19031        }
19032    }
19033
19034    @Override
19035    public void clearApplicationUserData(final String packageName,
19036            final IPackageDataObserver observer, final int userId) {
19037        mContext.enforceCallingOrSelfPermission(
19038                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19039
19040        final int callingUid = Binder.getCallingUid();
19041        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19042                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19043
19044        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19045        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19046        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19047            throw new SecurityException("Cannot clear data for a protected package: "
19048                    + packageName);
19049        }
19050        // Queue up an async operation since the package deletion may take a little while.
19051        mHandler.post(new Runnable() {
19052            public void run() {
19053                mHandler.removeCallbacks(this);
19054                final boolean succeeded;
19055                if (!filterApp) {
19056                    try (PackageFreezer freezer = freezePackage(packageName,
19057                            "clearApplicationUserData")) {
19058                        synchronized (mInstallLock) {
19059                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19060                        }
19061                        clearExternalStorageDataSync(packageName, userId, true);
19062                        synchronized (mPackages) {
19063                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19064                                    packageName, userId);
19065                        }
19066                    }
19067                    if (succeeded) {
19068                        // invoke DeviceStorageMonitor's update method to clear any notifications
19069                        DeviceStorageMonitorInternal dsm = LocalServices
19070                                .getService(DeviceStorageMonitorInternal.class);
19071                        if (dsm != null) {
19072                            dsm.checkMemory();
19073                        }
19074                    }
19075                } else {
19076                    succeeded = false;
19077                }
19078                if (observer != null) {
19079                    try {
19080                        observer.onRemoveCompleted(packageName, succeeded);
19081                    } catch (RemoteException e) {
19082                        Log.i(TAG, "Observer no longer exists.");
19083                    }
19084                } //end if observer
19085            } //end run
19086        });
19087    }
19088
19089    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19090        if (packageName == null) {
19091            Slog.w(TAG, "Attempt to delete null packageName.");
19092            return false;
19093        }
19094
19095        // Try finding details about the requested package
19096        PackageParser.Package pkg;
19097        synchronized (mPackages) {
19098            pkg = mPackages.get(packageName);
19099            if (pkg == null) {
19100                final PackageSetting ps = mSettings.mPackages.get(packageName);
19101                if (ps != null) {
19102                    pkg = ps.pkg;
19103                }
19104            }
19105
19106            if (pkg == null) {
19107                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19108                return false;
19109            }
19110
19111            PackageSetting ps = (PackageSetting) pkg.mExtras;
19112            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19113        }
19114
19115        clearAppDataLIF(pkg, userId,
19116                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19117
19118        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19119        removeKeystoreDataIfNeeded(userId, appId);
19120
19121        UserManagerInternal umInternal = getUserManagerInternal();
19122        final int flags;
19123        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19124            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19125        } else if (umInternal.isUserRunning(userId)) {
19126            flags = StorageManager.FLAG_STORAGE_DE;
19127        } else {
19128            flags = 0;
19129        }
19130        prepareAppDataContentsLIF(pkg, userId, flags);
19131
19132        return true;
19133    }
19134
19135    /**
19136     * Reverts user permission state changes (permissions and flags) in
19137     * all packages for a given user.
19138     *
19139     * @param userId The device user for which to do a reset.
19140     */
19141    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19142        final int packageCount = mPackages.size();
19143        for (int i = 0; i < packageCount; i++) {
19144            PackageParser.Package pkg = mPackages.valueAt(i);
19145            PackageSetting ps = (PackageSetting) pkg.mExtras;
19146            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19147        }
19148    }
19149
19150    private void resetNetworkPolicies(int userId) {
19151        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19152    }
19153
19154    /**
19155     * Reverts user permission state changes (permissions and flags).
19156     *
19157     * @param ps The package for which to reset.
19158     * @param userId The device user for which to do a reset.
19159     */
19160    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19161            final PackageSetting ps, final int userId) {
19162        if (ps.pkg == null) {
19163            return;
19164        }
19165
19166        // These are flags that can change base on user actions.
19167        final int userSettableMask = FLAG_PERMISSION_USER_SET
19168                | FLAG_PERMISSION_USER_FIXED
19169                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19170                | FLAG_PERMISSION_REVIEW_REQUIRED;
19171
19172        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19173                | FLAG_PERMISSION_POLICY_FIXED;
19174
19175        boolean writeInstallPermissions = false;
19176        boolean writeRuntimePermissions = false;
19177
19178        final int permissionCount = ps.pkg.requestedPermissions.size();
19179        for (int i = 0; i < permissionCount; i++) {
19180            final String permName = ps.pkg.requestedPermissions.get(i);
19181            final BasePermission bp =
19182                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19183            if (bp == null) {
19184                continue;
19185            }
19186
19187            // If shared user we just reset the state to which only this app contributed.
19188            if (ps.sharedUser != null) {
19189                boolean used = false;
19190                final int packageCount = ps.sharedUser.packages.size();
19191                for (int j = 0; j < packageCount; j++) {
19192                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19193                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19194                            && pkg.pkg.requestedPermissions.contains(permName)) {
19195                        used = true;
19196                        break;
19197                    }
19198                }
19199                if (used) {
19200                    continue;
19201                }
19202            }
19203
19204            final PermissionsState permissionsState = ps.getPermissionsState();
19205
19206            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19207
19208            // Always clear the user settable flags.
19209            final boolean hasInstallState =
19210                    permissionsState.getInstallPermissionState(permName) != null;
19211            // If permission review is enabled and this is a legacy app, mark the
19212            // permission as requiring a review as this is the initial state.
19213            int flags = 0;
19214            if (mSettings.mPermissions.mPermissionReviewRequired
19215                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19216                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19217            }
19218            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19219                if (hasInstallState) {
19220                    writeInstallPermissions = true;
19221                } else {
19222                    writeRuntimePermissions = true;
19223                }
19224            }
19225
19226            // Below is only runtime permission handling.
19227            if (!bp.isRuntime()) {
19228                continue;
19229            }
19230
19231            // Never clobber system or policy.
19232            if ((oldFlags & policyOrSystemFlags) != 0) {
19233                continue;
19234            }
19235
19236            // If this permission was granted by default, make sure it is.
19237            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19238                if (permissionsState.grantRuntimePermission(bp, userId)
19239                        != PERMISSION_OPERATION_FAILURE) {
19240                    writeRuntimePermissions = true;
19241                }
19242            // If permission review is enabled the permissions for a legacy apps
19243            // are represented as constantly granted runtime ones, so don't revoke.
19244            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19245                // Otherwise, reset the permission.
19246                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19247                switch (revokeResult) {
19248                    case PERMISSION_OPERATION_SUCCESS:
19249                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19250                        writeRuntimePermissions = true;
19251                        final int appId = ps.appId;
19252                        mHandler.post(new Runnable() {
19253                            @Override
19254                            public void run() {
19255                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19256                            }
19257                        });
19258                    } break;
19259                }
19260            }
19261        }
19262
19263        // Synchronously write as we are taking permissions away.
19264        if (writeRuntimePermissions) {
19265            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19266        }
19267
19268        // Synchronously write as we are taking permissions away.
19269        if (writeInstallPermissions) {
19270            mSettings.writeLPr();
19271        }
19272    }
19273
19274    /**
19275     * Remove entries from the keystore daemon. Will only remove it if the
19276     * {@code appId} is valid.
19277     */
19278    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19279        if (appId < 0) {
19280            return;
19281        }
19282
19283        final KeyStore keyStore = KeyStore.getInstance();
19284        if (keyStore != null) {
19285            if (userId == UserHandle.USER_ALL) {
19286                for (final int individual : sUserManager.getUserIds()) {
19287                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19288                }
19289            } else {
19290                keyStore.clearUid(UserHandle.getUid(userId, appId));
19291            }
19292        } else {
19293            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19294        }
19295    }
19296
19297    @Override
19298    public void deleteApplicationCacheFiles(final String packageName,
19299            final IPackageDataObserver observer) {
19300        final int userId = UserHandle.getCallingUserId();
19301        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19302    }
19303
19304    @Override
19305    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19306            final IPackageDataObserver observer) {
19307        final int callingUid = Binder.getCallingUid();
19308        if (mContext.checkCallingOrSelfPermission(
19309                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19310                != PackageManager.PERMISSION_GRANTED) {
19311            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19312            if (mContext.checkCallingOrSelfPermission(
19313                    android.Manifest.permission.DELETE_CACHE_FILES)
19314                    == PackageManager.PERMISSION_GRANTED) {
19315                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19316                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19317                        ", silently ignoring");
19318                return;
19319            }
19320            mContext.enforceCallingOrSelfPermission(
19321                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19322        }
19323        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19324                /* requireFullPermission= */ true, /* checkShell= */ false,
19325                "delete application cache files");
19326        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19327                android.Manifest.permission.ACCESS_INSTANT_APPS);
19328
19329        final PackageParser.Package pkg;
19330        synchronized (mPackages) {
19331            pkg = mPackages.get(packageName);
19332        }
19333
19334        // Queue up an async operation since the package deletion may take a little while.
19335        mHandler.post(new Runnable() {
19336            public void run() {
19337                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19338                boolean doClearData = true;
19339                if (ps != null) {
19340                    final boolean targetIsInstantApp =
19341                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19342                    doClearData = !targetIsInstantApp
19343                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19344                }
19345                if (doClearData) {
19346                    synchronized (mInstallLock) {
19347                        final int flags = StorageManager.FLAG_STORAGE_DE
19348                                | StorageManager.FLAG_STORAGE_CE;
19349                        // We're only clearing cache files, so we don't care if the
19350                        // app is unfrozen and still able to run
19351                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19352                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19353                    }
19354                    clearExternalStorageDataSync(packageName, userId, false);
19355                }
19356                if (observer != null) {
19357                    try {
19358                        observer.onRemoveCompleted(packageName, true);
19359                    } catch (RemoteException e) {
19360                        Log.i(TAG, "Observer no longer exists.");
19361                    }
19362                }
19363            }
19364        });
19365    }
19366
19367    @Override
19368    public void getPackageSizeInfo(final String packageName, int userHandle,
19369            final IPackageStatsObserver observer) {
19370        throw new UnsupportedOperationException(
19371                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19372    }
19373
19374    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19375        final PackageSetting ps;
19376        synchronized (mPackages) {
19377            ps = mSettings.mPackages.get(packageName);
19378            if (ps == null) {
19379                Slog.w(TAG, "Failed to find settings for " + packageName);
19380                return false;
19381            }
19382        }
19383
19384        final String[] packageNames = { packageName };
19385        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19386        final String[] codePaths = { ps.codePathString };
19387
19388        try {
19389            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19390                    ps.appId, ceDataInodes, codePaths, stats);
19391
19392            // For now, ignore code size of packages on system partition
19393            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19394                stats.codeSize = 0;
19395            }
19396
19397            // External clients expect these to be tracked separately
19398            stats.dataSize -= stats.cacheSize;
19399
19400        } catch (InstallerException e) {
19401            Slog.w(TAG, String.valueOf(e));
19402            return false;
19403        }
19404
19405        return true;
19406    }
19407
19408    private int getUidTargetSdkVersionLockedLPr(int uid) {
19409        Object obj = mSettings.getUserIdLPr(uid);
19410        if (obj instanceof SharedUserSetting) {
19411            final SharedUserSetting sus = (SharedUserSetting) obj;
19412            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19413            final Iterator<PackageSetting> it = sus.packages.iterator();
19414            while (it.hasNext()) {
19415                final PackageSetting ps = it.next();
19416                if (ps.pkg != null) {
19417                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19418                    if (v < vers) vers = v;
19419                }
19420            }
19421            return vers;
19422        } else if (obj instanceof PackageSetting) {
19423            final PackageSetting ps = (PackageSetting) obj;
19424            if (ps.pkg != null) {
19425                return ps.pkg.applicationInfo.targetSdkVersion;
19426            }
19427        }
19428        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19429    }
19430
19431    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19432        final PackageParser.Package p = mPackages.get(packageName);
19433        if (p != null) {
19434            return p.applicationInfo.targetSdkVersion;
19435        }
19436        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19437    }
19438
19439    @Override
19440    public void addPreferredActivity(IntentFilter filter, int match,
19441            ComponentName[] set, ComponentName activity, int userId) {
19442        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19443                "Adding preferred");
19444    }
19445
19446    private void addPreferredActivityInternal(IntentFilter filter, int match,
19447            ComponentName[] set, ComponentName activity, boolean always, int userId,
19448            String opname) {
19449        // writer
19450        int callingUid = Binder.getCallingUid();
19451        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19452                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19453        if (filter.countActions() == 0) {
19454            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19455            return;
19456        }
19457        synchronized (mPackages) {
19458            if (mContext.checkCallingOrSelfPermission(
19459                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19460                    != PackageManager.PERMISSION_GRANTED) {
19461                if (getUidTargetSdkVersionLockedLPr(callingUid)
19462                        < Build.VERSION_CODES.FROYO) {
19463                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19464                            + callingUid);
19465                    return;
19466                }
19467                mContext.enforceCallingOrSelfPermission(
19468                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19469            }
19470
19471            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19472            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19473                    + userId + ":");
19474            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19475            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19476            scheduleWritePackageRestrictionsLocked(userId);
19477            postPreferredActivityChangedBroadcast(userId);
19478        }
19479    }
19480
19481    private void postPreferredActivityChangedBroadcast(int userId) {
19482        mHandler.post(() -> {
19483            final IActivityManager am = ActivityManager.getService();
19484            if (am == null) {
19485                return;
19486            }
19487
19488            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19489            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19490            try {
19491                am.broadcastIntent(null, intent, null, null,
19492                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19493                        null, false, false, userId);
19494            } catch (RemoteException e) {
19495            }
19496        });
19497    }
19498
19499    @Override
19500    public void replacePreferredActivity(IntentFilter filter, int match,
19501            ComponentName[] set, ComponentName activity, int userId) {
19502        if (filter.countActions() != 1) {
19503            throw new IllegalArgumentException(
19504                    "replacePreferredActivity expects filter to have only 1 action.");
19505        }
19506        if (filter.countDataAuthorities() != 0
19507                || filter.countDataPaths() != 0
19508                || filter.countDataSchemes() > 1
19509                || filter.countDataTypes() != 0) {
19510            throw new IllegalArgumentException(
19511                    "replacePreferredActivity expects filter to have no data authorities, " +
19512                    "paths, or types; and at most one scheme.");
19513        }
19514
19515        final int callingUid = Binder.getCallingUid();
19516        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19517                true /* requireFullPermission */, false /* checkShell */,
19518                "replace preferred activity");
19519        synchronized (mPackages) {
19520            if (mContext.checkCallingOrSelfPermission(
19521                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19522                    != PackageManager.PERMISSION_GRANTED) {
19523                if (getUidTargetSdkVersionLockedLPr(callingUid)
19524                        < Build.VERSION_CODES.FROYO) {
19525                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19526                            + Binder.getCallingUid());
19527                    return;
19528                }
19529                mContext.enforceCallingOrSelfPermission(
19530                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19531            }
19532
19533            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19534            if (pir != null) {
19535                // Get all of the existing entries that exactly match this filter.
19536                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19537                if (existing != null && existing.size() == 1) {
19538                    PreferredActivity cur = existing.get(0);
19539                    if (DEBUG_PREFERRED) {
19540                        Slog.i(TAG, "Checking replace of preferred:");
19541                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19542                        if (!cur.mPref.mAlways) {
19543                            Slog.i(TAG, "  -- CUR; not mAlways!");
19544                        } else {
19545                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19546                            Slog.i(TAG, "  -- CUR: mSet="
19547                                    + Arrays.toString(cur.mPref.mSetComponents));
19548                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19549                            Slog.i(TAG, "  -- NEW: mMatch="
19550                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19551                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19552                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19553                        }
19554                    }
19555                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19556                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19557                            && cur.mPref.sameSet(set)) {
19558                        // Setting the preferred activity to what it happens to be already
19559                        if (DEBUG_PREFERRED) {
19560                            Slog.i(TAG, "Replacing with same preferred activity "
19561                                    + cur.mPref.mShortComponent + " for user "
19562                                    + userId + ":");
19563                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19564                        }
19565                        return;
19566                    }
19567                }
19568
19569                if (existing != null) {
19570                    if (DEBUG_PREFERRED) {
19571                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19572                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19573                    }
19574                    for (int i = 0; i < existing.size(); i++) {
19575                        PreferredActivity pa = existing.get(i);
19576                        if (DEBUG_PREFERRED) {
19577                            Slog.i(TAG, "Removing existing preferred activity "
19578                                    + pa.mPref.mComponent + ":");
19579                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19580                        }
19581                        pir.removeFilter(pa);
19582                    }
19583                }
19584            }
19585            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19586                    "Replacing preferred");
19587        }
19588    }
19589
19590    @Override
19591    public void clearPackagePreferredActivities(String packageName) {
19592        final int callingUid = Binder.getCallingUid();
19593        if (getInstantAppPackageName(callingUid) != null) {
19594            return;
19595        }
19596        // writer
19597        synchronized (mPackages) {
19598            PackageParser.Package pkg = mPackages.get(packageName);
19599            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19600                if (mContext.checkCallingOrSelfPermission(
19601                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19602                        != PackageManager.PERMISSION_GRANTED) {
19603                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19604                            < Build.VERSION_CODES.FROYO) {
19605                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19606                                + callingUid);
19607                        return;
19608                    }
19609                    mContext.enforceCallingOrSelfPermission(
19610                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19611                }
19612            }
19613            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19614            if (ps != null
19615                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19616                return;
19617            }
19618            int user = UserHandle.getCallingUserId();
19619            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19620                scheduleWritePackageRestrictionsLocked(user);
19621            }
19622        }
19623    }
19624
19625    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19626    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19627        ArrayList<PreferredActivity> removed = null;
19628        boolean changed = false;
19629        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19630            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19631            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19632            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19633                continue;
19634            }
19635            Iterator<PreferredActivity> it = pir.filterIterator();
19636            while (it.hasNext()) {
19637                PreferredActivity pa = it.next();
19638                // Mark entry for removal only if it matches the package name
19639                // and the entry is of type "always".
19640                if (packageName == null ||
19641                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19642                                && pa.mPref.mAlways)) {
19643                    if (removed == null) {
19644                        removed = new ArrayList<PreferredActivity>();
19645                    }
19646                    removed.add(pa);
19647                }
19648            }
19649            if (removed != null) {
19650                for (int j=0; j<removed.size(); j++) {
19651                    PreferredActivity pa = removed.get(j);
19652                    pir.removeFilter(pa);
19653                }
19654                changed = true;
19655            }
19656        }
19657        if (changed) {
19658            postPreferredActivityChangedBroadcast(userId);
19659        }
19660        return changed;
19661    }
19662
19663    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19664    private void clearIntentFilterVerificationsLPw(int userId) {
19665        final int packageCount = mPackages.size();
19666        for (int i = 0; i < packageCount; i++) {
19667            PackageParser.Package pkg = mPackages.valueAt(i);
19668            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19669        }
19670    }
19671
19672    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19673    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19674        if (userId == UserHandle.USER_ALL) {
19675            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19676                    sUserManager.getUserIds())) {
19677                for (int oneUserId : sUserManager.getUserIds()) {
19678                    scheduleWritePackageRestrictionsLocked(oneUserId);
19679                }
19680            }
19681        } else {
19682            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19683                scheduleWritePackageRestrictionsLocked(userId);
19684            }
19685        }
19686    }
19687
19688    /** Clears state for all users, and touches intent filter verification policy */
19689    void clearDefaultBrowserIfNeeded(String packageName) {
19690        for (int oneUserId : sUserManager.getUserIds()) {
19691            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19692        }
19693    }
19694
19695    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19696        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19697        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19698            if (packageName.equals(defaultBrowserPackageName)) {
19699                setDefaultBrowserPackageName(null, userId);
19700            }
19701        }
19702    }
19703
19704    @Override
19705    public void resetApplicationPreferences(int userId) {
19706        mContext.enforceCallingOrSelfPermission(
19707                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19708        final long identity = Binder.clearCallingIdentity();
19709        // writer
19710        try {
19711            synchronized (mPackages) {
19712                clearPackagePreferredActivitiesLPw(null, userId);
19713                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19714                // TODO: We have to reset the default SMS and Phone. This requires
19715                // significant refactoring to keep all default apps in the package
19716                // manager (cleaner but more work) or have the services provide
19717                // callbacks to the package manager to request a default app reset.
19718                applyFactoryDefaultBrowserLPw(userId);
19719                clearIntentFilterVerificationsLPw(userId);
19720                primeDomainVerificationsLPw(userId);
19721                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19722                scheduleWritePackageRestrictionsLocked(userId);
19723            }
19724            resetNetworkPolicies(userId);
19725        } finally {
19726            Binder.restoreCallingIdentity(identity);
19727        }
19728    }
19729
19730    @Override
19731    public int getPreferredActivities(List<IntentFilter> outFilters,
19732            List<ComponentName> outActivities, String packageName) {
19733        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19734            return 0;
19735        }
19736        int num = 0;
19737        final int userId = UserHandle.getCallingUserId();
19738        // reader
19739        synchronized (mPackages) {
19740            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19741            if (pir != null) {
19742                final Iterator<PreferredActivity> it = pir.filterIterator();
19743                while (it.hasNext()) {
19744                    final PreferredActivity pa = it.next();
19745                    if (packageName == null
19746                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19747                                    && pa.mPref.mAlways)) {
19748                        if (outFilters != null) {
19749                            outFilters.add(new IntentFilter(pa));
19750                        }
19751                        if (outActivities != null) {
19752                            outActivities.add(pa.mPref.mComponent);
19753                        }
19754                    }
19755                }
19756            }
19757        }
19758
19759        return num;
19760    }
19761
19762    @Override
19763    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19764            int userId) {
19765        int callingUid = Binder.getCallingUid();
19766        if (callingUid != Process.SYSTEM_UID) {
19767            throw new SecurityException(
19768                    "addPersistentPreferredActivity can only be run by the system");
19769        }
19770        if (filter.countActions() == 0) {
19771            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19772            return;
19773        }
19774        synchronized (mPackages) {
19775            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19776                    ":");
19777            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19778            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19779                    new PersistentPreferredActivity(filter, activity));
19780            scheduleWritePackageRestrictionsLocked(userId);
19781            postPreferredActivityChangedBroadcast(userId);
19782        }
19783    }
19784
19785    @Override
19786    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19787        int callingUid = Binder.getCallingUid();
19788        if (callingUid != Process.SYSTEM_UID) {
19789            throw new SecurityException(
19790                    "clearPackagePersistentPreferredActivities can only be run by the system");
19791        }
19792        ArrayList<PersistentPreferredActivity> removed = null;
19793        boolean changed = false;
19794        synchronized (mPackages) {
19795            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19796                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19797                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19798                        .valueAt(i);
19799                if (userId != thisUserId) {
19800                    continue;
19801                }
19802                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19803                while (it.hasNext()) {
19804                    PersistentPreferredActivity ppa = it.next();
19805                    // Mark entry for removal only if it matches the package name.
19806                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19807                        if (removed == null) {
19808                            removed = new ArrayList<PersistentPreferredActivity>();
19809                        }
19810                        removed.add(ppa);
19811                    }
19812                }
19813                if (removed != null) {
19814                    for (int j=0; j<removed.size(); j++) {
19815                        PersistentPreferredActivity ppa = removed.get(j);
19816                        ppir.removeFilter(ppa);
19817                    }
19818                    changed = true;
19819                }
19820            }
19821
19822            if (changed) {
19823                scheduleWritePackageRestrictionsLocked(userId);
19824                postPreferredActivityChangedBroadcast(userId);
19825            }
19826        }
19827    }
19828
19829    /**
19830     * Common machinery for picking apart a restored XML blob and passing
19831     * it to a caller-supplied functor to be applied to the running system.
19832     */
19833    private void restoreFromXml(XmlPullParser parser, int userId,
19834            String expectedStartTag, BlobXmlRestorer functor)
19835            throws IOException, XmlPullParserException {
19836        int type;
19837        while ((type = parser.next()) != XmlPullParser.START_TAG
19838                && type != XmlPullParser.END_DOCUMENT) {
19839        }
19840        if (type != XmlPullParser.START_TAG) {
19841            // oops didn't find a start tag?!
19842            if (DEBUG_BACKUP) {
19843                Slog.e(TAG, "Didn't find start tag during restore");
19844            }
19845            return;
19846        }
19847Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19848        // this is supposed to be TAG_PREFERRED_BACKUP
19849        if (!expectedStartTag.equals(parser.getName())) {
19850            if (DEBUG_BACKUP) {
19851                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19852            }
19853            return;
19854        }
19855
19856        // skip interfering stuff, then we're aligned with the backing implementation
19857        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19858Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19859        functor.apply(parser, userId);
19860    }
19861
19862    private interface BlobXmlRestorer {
19863        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19864    }
19865
19866    /**
19867     * Non-Binder method, support for the backup/restore mechanism: write the
19868     * full set of preferred activities in its canonical XML format.  Returns the
19869     * XML output as a byte array, or null if there is none.
19870     */
19871    @Override
19872    public byte[] getPreferredActivityBackup(int userId) {
19873        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19874            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19875        }
19876
19877        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19878        try {
19879            final XmlSerializer serializer = new FastXmlSerializer();
19880            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19881            serializer.startDocument(null, true);
19882            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19883
19884            synchronized (mPackages) {
19885                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19886            }
19887
19888            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19889            serializer.endDocument();
19890            serializer.flush();
19891        } catch (Exception e) {
19892            if (DEBUG_BACKUP) {
19893                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19894            }
19895            return null;
19896        }
19897
19898        return dataStream.toByteArray();
19899    }
19900
19901    @Override
19902    public void restorePreferredActivities(byte[] backup, int userId) {
19903        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19904            throw new SecurityException("Only the system may call restorePreferredActivities()");
19905        }
19906
19907        try {
19908            final XmlPullParser parser = Xml.newPullParser();
19909            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19910            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19911                    new BlobXmlRestorer() {
19912                        @Override
19913                        public void apply(XmlPullParser parser, int userId)
19914                                throws XmlPullParserException, IOException {
19915                            synchronized (mPackages) {
19916                                mSettings.readPreferredActivitiesLPw(parser, userId);
19917                            }
19918                        }
19919                    } );
19920        } catch (Exception e) {
19921            if (DEBUG_BACKUP) {
19922                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19923            }
19924        }
19925    }
19926
19927    /**
19928     * Non-Binder method, support for the backup/restore mechanism: write the
19929     * default browser (etc) settings in its canonical XML format.  Returns the default
19930     * browser XML representation as a byte array, or null if there is none.
19931     */
19932    @Override
19933    public byte[] getDefaultAppsBackup(int userId) {
19934        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19935            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19936        }
19937
19938        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19939        try {
19940            final XmlSerializer serializer = new FastXmlSerializer();
19941            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19942            serializer.startDocument(null, true);
19943            serializer.startTag(null, TAG_DEFAULT_APPS);
19944
19945            synchronized (mPackages) {
19946                mSettings.writeDefaultAppsLPr(serializer, userId);
19947            }
19948
19949            serializer.endTag(null, TAG_DEFAULT_APPS);
19950            serializer.endDocument();
19951            serializer.flush();
19952        } catch (Exception e) {
19953            if (DEBUG_BACKUP) {
19954                Slog.e(TAG, "Unable to write default apps for backup", e);
19955            }
19956            return null;
19957        }
19958
19959        return dataStream.toByteArray();
19960    }
19961
19962    @Override
19963    public void restoreDefaultApps(byte[] backup, int userId) {
19964        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19965            throw new SecurityException("Only the system may call restoreDefaultApps()");
19966        }
19967
19968        try {
19969            final XmlPullParser parser = Xml.newPullParser();
19970            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19971            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19972                    new BlobXmlRestorer() {
19973                        @Override
19974                        public void apply(XmlPullParser parser, int userId)
19975                                throws XmlPullParserException, IOException {
19976                            synchronized (mPackages) {
19977                                mSettings.readDefaultAppsLPw(parser, userId);
19978                            }
19979                        }
19980                    } );
19981        } catch (Exception e) {
19982            if (DEBUG_BACKUP) {
19983                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19984            }
19985        }
19986    }
19987
19988    @Override
19989    public byte[] getIntentFilterVerificationBackup(int userId) {
19990        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19991            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19992        }
19993
19994        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19995        try {
19996            final XmlSerializer serializer = new FastXmlSerializer();
19997            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19998            serializer.startDocument(null, true);
19999            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20000
20001            synchronized (mPackages) {
20002                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20003            }
20004
20005            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20006            serializer.endDocument();
20007            serializer.flush();
20008        } catch (Exception e) {
20009            if (DEBUG_BACKUP) {
20010                Slog.e(TAG, "Unable to write default apps for backup", e);
20011            }
20012            return null;
20013        }
20014
20015        return dataStream.toByteArray();
20016    }
20017
20018    @Override
20019    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20020        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20021            throw new SecurityException("Only the system may call restorePreferredActivities()");
20022        }
20023
20024        try {
20025            final XmlPullParser parser = Xml.newPullParser();
20026            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20027            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20028                    new BlobXmlRestorer() {
20029                        @Override
20030                        public void apply(XmlPullParser parser, int userId)
20031                                throws XmlPullParserException, IOException {
20032                            synchronized (mPackages) {
20033                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20034                                mSettings.writeLPr();
20035                            }
20036                        }
20037                    } );
20038        } catch (Exception e) {
20039            if (DEBUG_BACKUP) {
20040                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20041            }
20042        }
20043    }
20044
20045    @Override
20046    public byte[] getPermissionGrantBackup(int userId) {
20047        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20048            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20049        }
20050
20051        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20052        try {
20053            final XmlSerializer serializer = new FastXmlSerializer();
20054            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20055            serializer.startDocument(null, true);
20056            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20057
20058            synchronized (mPackages) {
20059                serializeRuntimePermissionGrantsLPr(serializer, userId);
20060            }
20061
20062            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20063            serializer.endDocument();
20064            serializer.flush();
20065        } catch (Exception e) {
20066            if (DEBUG_BACKUP) {
20067                Slog.e(TAG, "Unable to write default apps for backup", e);
20068            }
20069            return null;
20070        }
20071
20072        return dataStream.toByteArray();
20073    }
20074
20075    @Override
20076    public void restorePermissionGrants(byte[] backup, int userId) {
20077        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20078            throw new SecurityException("Only the system may call restorePermissionGrants()");
20079        }
20080
20081        try {
20082            final XmlPullParser parser = Xml.newPullParser();
20083            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20084            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20085                    new BlobXmlRestorer() {
20086                        @Override
20087                        public void apply(XmlPullParser parser, int userId)
20088                                throws XmlPullParserException, IOException {
20089                            synchronized (mPackages) {
20090                                processRestoredPermissionGrantsLPr(parser, userId);
20091                            }
20092                        }
20093                    } );
20094        } catch (Exception e) {
20095            if (DEBUG_BACKUP) {
20096                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20097            }
20098        }
20099    }
20100
20101    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20102            throws IOException {
20103        serializer.startTag(null, TAG_ALL_GRANTS);
20104
20105        final int N = mSettings.mPackages.size();
20106        for (int i = 0; i < N; i++) {
20107            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20108            boolean pkgGrantsKnown = false;
20109
20110            PermissionsState packagePerms = ps.getPermissionsState();
20111
20112            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20113                final int grantFlags = state.getFlags();
20114                // only look at grants that are not system/policy fixed
20115                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20116                    final boolean isGranted = state.isGranted();
20117                    // And only back up the user-twiddled state bits
20118                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20119                        final String packageName = mSettings.mPackages.keyAt(i);
20120                        if (!pkgGrantsKnown) {
20121                            serializer.startTag(null, TAG_GRANT);
20122                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20123                            pkgGrantsKnown = true;
20124                        }
20125
20126                        final boolean userSet =
20127                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20128                        final boolean userFixed =
20129                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20130                        final boolean revoke =
20131                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20132
20133                        serializer.startTag(null, TAG_PERMISSION);
20134                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20135                        if (isGranted) {
20136                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20137                        }
20138                        if (userSet) {
20139                            serializer.attribute(null, ATTR_USER_SET, "true");
20140                        }
20141                        if (userFixed) {
20142                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20143                        }
20144                        if (revoke) {
20145                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20146                        }
20147                        serializer.endTag(null, TAG_PERMISSION);
20148                    }
20149                }
20150            }
20151
20152            if (pkgGrantsKnown) {
20153                serializer.endTag(null, TAG_GRANT);
20154            }
20155        }
20156
20157        serializer.endTag(null, TAG_ALL_GRANTS);
20158    }
20159
20160    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20161            throws XmlPullParserException, IOException {
20162        String pkgName = null;
20163        int outerDepth = parser.getDepth();
20164        int type;
20165        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20166                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20167            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20168                continue;
20169            }
20170
20171            final String tagName = parser.getName();
20172            if (tagName.equals(TAG_GRANT)) {
20173                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20174                if (DEBUG_BACKUP) {
20175                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20176                }
20177            } else if (tagName.equals(TAG_PERMISSION)) {
20178
20179                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20180                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20181
20182                int newFlagSet = 0;
20183                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20184                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20185                }
20186                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20187                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20188                }
20189                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20190                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20191                }
20192                if (DEBUG_BACKUP) {
20193                    Slog.v(TAG, "  + Restoring grant:"
20194                            + " pkg=" + pkgName
20195                            + " perm=" + permName
20196                            + " granted=" + isGranted
20197                            + " bits=0x" + Integer.toHexString(newFlagSet));
20198                }
20199                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20200                if (ps != null) {
20201                    // Already installed so we apply the grant immediately
20202                    if (DEBUG_BACKUP) {
20203                        Slog.v(TAG, "        + already installed; applying");
20204                    }
20205                    PermissionsState perms = ps.getPermissionsState();
20206                    BasePermission bp =
20207                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20208                    if (bp != null) {
20209                        if (isGranted) {
20210                            perms.grantRuntimePermission(bp, userId);
20211                        }
20212                        if (newFlagSet != 0) {
20213                            perms.updatePermissionFlags(
20214                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20215                        }
20216                    }
20217                } else {
20218                    // Need to wait for post-restore install to apply the grant
20219                    if (DEBUG_BACKUP) {
20220                        Slog.v(TAG, "        - not yet installed; saving for later");
20221                    }
20222                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20223                            isGranted, newFlagSet, userId);
20224                }
20225            } else {
20226                PackageManagerService.reportSettingsProblem(Log.WARN,
20227                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20228                XmlUtils.skipCurrentTag(parser);
20229            }
20230        }
20231
20232        scheduleWriteSettingsLocked();
20233        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20234    }
20235
20236    @Override
20237    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20238            int sourceUserId, int targetUserId, int flags) {
20239        mContext.enforceCallingOrSelfPermission(
20240                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20241        int callingUid = Binder.getCallingUid();
20242        enforceOwnerRights(ownerPackage, callingUid);
20243        PackageManagerServiceUtils.enforceShellRestriction(
20244                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20245        if (intentFilter.countActions() == 0) {
20246            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20247            return;
20248        }
20249        synchronized (mPackages) {
20250            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20251                    ownerPackage, targetUserId, flags);
20252            CrossProfileIntentResolver resolver =
20253                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20254            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20255            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20256            if (existing != null) {
20257                int size = existing.size();
20258                for (int i = 0; i < size; i++) {
20259                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20260                        return;
20261                    }
20262                }
20263            }
20264            resolver.addFilter(newFilter);
20265            scheduleWritePackageRestrictionsLocked(sourceUserId);
20266        }
20267    }
20268
20269    @Override
20270    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20271        mContext.enforceCallingOrSelfPermission(
20272                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20273        final int callingUid = Binder.getCallingUid();
20274        enforceOwnerRights(ownerPackage, callingUid);
20275        PackageManagerServiceUtils.enforceShellRestriction(
20276                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20277        synchronized (mPackages) {
20278            CrossProfileIntentResolver resolver =
20279                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20280            ArraySet<CrossProfileIntentFilter> set =
20281                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20282            for (CrossProfileIntentFilter filter : set) {
20283                if (filter.getOwnerPackage().equals(ownerPackage)) {
20284                    resolver.removeFilter(filter);
20285                }
20286            }
20287            scheduleWritePackageRestrictionsLocked(sourceUserId);
20288        }
20289    }
20290
20291    // Enforcing that callingUid is owning pkg on userId
20292    private void enforceOwnerRights(String pkg, int callingUid) {
20293        // The system owns everything.
20294        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20295            return;
20296        }
20297        final int callingUserId = UserHandle.getUserId(callingUid);
20298        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20299        if (pi == null) {
20300            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20301                    + callingUserId);
20302        }
20303        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20304            throw new SecurityException("Calling uid " + callingUid
20305                    + " does not own package " + pkg);
20306        }
20307    }
20308
20309    @Override
20310    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20311        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20312            return null;
20313        }
20314        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20315    }
20316
20317    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20318        UserManagerService ums = UserManagerService.getInstance();
20319        if (ums != null) {
20320            final UserInfo parent = ums.getProfileParent(userId);
20321            final int launcherUid = (parent != null) ? parent.id : userId;
20322            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20323            if (launcherComponent != null) {
20324                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20325                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20326                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20327                        .setPackage(launcherComponent.getPackageName());
20328                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20329            }
20330        }
20331    }
20332
20333    /**
20334     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20335     * then reports the most likely home activity or null if there are more than one.
20336     */
20337    private ComponentName getDefaultHomeActivity(int userId) {
20338        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20339        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20340        if (cn != null) {
20341            return cn;
20342        }
20343
20344        // Find the launcher with the highest priority and return that component if there are no
20345        // other home activity with the same priority.
20346        int lastPriority = Integer.MIN_VALUE;
20347        ComponentName lastComponent = null;
20348        final int size = allHomeCandidates.size();
20349        for (int i = 0; i < size; i++) {
20350            final ResolveInfo ri = allHomeCandidates.get(i);
20351            if (ri.priority > lastPriority) {
20352                lastComponent = ri.activityInfo.getComponentName();
20353                lastPriority = ri.priority;
20354            } else if (ri.priority == lastPriority) {
20355                // Two components found with same priority.
20356                lastComponent = null;
20357            }
20358        }
20359        return lastComponent;
20360    }
20361
20362    private Intent getHomeIntent() {
20363        Intent intent = new Intent(Intent.ACTION_MAIN);
20364        intent.addCategory(Intent.CATEGORY_HOME);
20365        intent.addCategory(Intent.CATEGORY_DEFAULT);
20366        return intent;
20367    }
20368
20369    private IntentFilter getHomeFilter() {
20370        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20371        filter.addCategory(Intent.CATEGORY_HOME);
20372        filter.addCategory(Intent.CATEGORY_DEFAULT);
20373        return filter;
20374    }
20375
20376    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20377            int userId) {
20378        Intent intent  = getHomeIntent();
20379        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20380                PackageManager.GET_META_DATA, userId);
20381        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20382                true, false, false, userId);
20383
20384        allHomeCandidates.clear();
20385        if (list != null) {
20386            for (ResolveInfo ri : list) {
20387                allHomeCandidates.add(ri);
20388            }
20389        }
20390        return (preferred == null || preferred.activityInfo == null)
20391                ? null
20392                : new ComponentName(preferred.activityInfo.packageName,
20393                        preferred.activityInfo.name);
20394    }
20395
20396    @Override
20397    public void setHomeActivity(ComponentName comp, int userId) {
20398        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20399            return;
20400        }
20401        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20402        getHomeActivitiesAsUser(homeActivities, userId);
20403
20404        boolean found = false;
20405
20406        final int size = homeActivities.size();
20407        final ComponentName[] set = new ComponentName[size];
20408        for (int i = 0; i < size; i++) {
20409            final ResolveInfo candidate = homeActivities.get(i);
20410            final ActivityInfo info = candidate.activityInfo;
20411            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20412            set[i] = activityName;
20413            if (!found && activityName.equals(comp)) {
20414                found = true;
20415            }
20416        }
20417        if (!found) {
20418            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20419                    + userId);
20420        }
20421        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20422                set, comp, userId);
20423    }
20424
20425    private @Nullable String getSetupWizardPackageName() {
20426        final Intent intent = new Intent(Intent.ACTION_MAIN);
20427        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20428
20429        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20430                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20431                        | MATCH_DISABLED_COMPONENTS,
20432                UserHandle.myUserId());
20433        if (matches.size() == 1) {
20434            return matches.get(0).getComponentInfo().packageName;
20435        } else {
20436            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20437                    + ": matches=" + matches);
20438            return null;
20439        }
20440    }
20441
20442    private @Nullable String getStorageManagerPackageName() {
20443        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20444
20445        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20446                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20447                        | MATCH_DISABLED_COMPONENTS,
20448                UserHandle.myUserId());
20449        if (matches.size() == 1) {
20450            return matches.get(0).getComponentInfo().packageName;
20451        } else {
20452            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20453                    + matches.size() + ": matches=" + matches);
20454            return null;
20455        }
20456    }
20457
20458    @Override
20459    public String getSystemTextClassifierPackageName() {
20460        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20461    }
20462
20463    @Override
20464    public void setApplicationEnabledSetting(String appPackageName,
20465            int newState, int flags, int userId, String callingPackage) {
20466        if (!sUserManager.exists(userId)) return;
20467        if (callingPackage == null) {
20468            callingPackage = Integer.toString(Binder.getCallingUid());
20469        }
20470        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20471    }
20472
20473    @Override
20474    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20475        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20476        synchronized (mPackages) {
20477            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20478            if (pkgSetting != null) {
20479                pkgSetting.setUpdateAvailable(updateAvailable);
20480            }
20481        }
20482    }
20483
20484    @Override
20485    public void setComponentEnabledSetting(ComponentName componentName,
20486            int newState, int flags, int userId) {
20487        if (!sUserManager.exists(userId)) return;
20488        setEnabledSetting(componentName.getPackageName(),
20489                componentName.getClassName(), newState, flags, userId, null);
20490    }
20491
20492    private void setEnabledSetting(final String packageName, String className, int newState,
20493            final int flags, int userId, String callingPackage) {
20494        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20495              || newState == COMPONENT_ENABLED_STATE_ENABLED
20496              || newState == COMPONENT_ENABLED_STATE_DISABLED
20497              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20498              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20499            throw new IllegalArgumentException("Invalid new component state: "
20500                    + newState);
20501        }
20502        PackageSetting pkgSetting;
20503        final int callingUid = Binder.getCallingUid();
20504        final int permission;
20505        if (callingUid == Process.SYSTEM_UID) {
20506            permission = PackageManager.PERMISSION_GRANTED;
20507        } else {
20508            permission = mContext.checkCallingOrSelfPermission(
20509                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20510        }
20511        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20512                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20513        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20514        boolean sendNow = false;
20515        boolean isApp = (className == null);
20516        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20517        String componentName = isApp ? packageName : className;
20518        int packageUid = -1;
20519        ArrayList<String> components;
20520
20521        // reader
20522        synchronized (mPackages) {
20523            pkgSetting = mSettings.mPackages.get(packageName);
20524            if (pkgSetting == null) {
20525                if (!isCallerInstantApp) {
20526                    if (className == null) {
20527                        throw new IllegalArgumentException("Unknown package: " + packageName);
20528                    }
20529                    throw new IllegalArgumentException(
20530                            "Unknown component: " + packageName + "/" + className);
20531                } else {
20532                    // throw SecurityException to prevent leaking package information
20533                    throw new SecurityException(
20534                            "Attempt to change component state; "
20535                            + "pid=" + Binder.getCallingPid()
20536                            + ", uid=" + callingUid
20537                            + (className == null
20538                                    ? ", package=" + packageName
20539                                    : ", component=" + packageName + "/" + className));
20540                }
20541            }
20542        }
20543
20544        // Limit who can change which apps
20545        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20546            // Don't allow apps that don't have permission to modify other apps
20547            if (!allowedByPermission
20548                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20549                throw new SecurityException(
20550                        "Attempt to change component state; "
20551                        + "pid=" + Binder.getCallingPid()
20552                        + ", uid=" + callingUid
20553                        + (className == null
20554                                ? ", package=" + packageName
20555                                : ", component=" + packageName + "/" + className));
20556            }
20557            // Don't allow changing protected packages.
20558            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20559                throw new SecurityException("Cannot disable a protected package: " + packageName);
20560            }
20561        }
20562
20563        synchronized (mPackages) {
20564            if (callingUid == Process.SHELL_UID
20565                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20566                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20567                // unless it is a test package.
20568                int oldState = pkgSetting.getEnabled(userId);
20569                if (className == null
20570                        &&
20571                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20572                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20573                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20574                        &&
20575                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20576                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20577                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20578                    // ok
20579                } else {
20580                    throw new SecurityException(
20581                            "Shell cannot change component state for " + packageName + "/"
20582                                    + className + " to " + newState);
20583                }
20584            }
20585        }
20586        if (className == null) {
20587            // We're dealing with an application/package level state change
20588            synchronized (mPackages) {
20589                if (pkgSetting.getEnabled(userId) == newState) {
20590                    // Nothing to do
20591                    return;
20592                }
20593            }
20594            // If we're enabling a system stub, there's a little more work to do.
20595            // Prior to enabling the package, we need to decompress the APK(s) to the
20596            // data partition and then replace the version on the system partition.
20597            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20598            final boolean isSystemStub = deletedPkg.isStub
20599                    && deletedPkg.isSystem();
20600            if (isSystemStub
20601                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20602                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20603                final File codePath = decompressPackage(deletedPkg);
20604                if (codePath == null) {
20605                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20606                    return;
20607                }
20608                // TODO remove direct parsing of the package object during internal cleanup
20609                // of scan package
20610                // We need to call parse directly here for no other reason than we need
20611                // the new package in order to disable the old one [we use the information
20612                // for some internal optimization to optionally create a new package setting
20613                // object on replace]. However, we can't get the package from the scan
20614                // because the scan modifies live structures and we need to remove the
20615                // old [system] package from the system before a scan can be attempted.
20616                // Once scan is indempotent we can remove this parse and use the package
20617                // object we scanned, prior to adding it to package settings.
20618                final PackageParser pp = new PackageParser();
20619                pp.setSeparateProcesses(mSeparateProcesses);
20620                pp.setDisplayMetrics(mMetrics);
20621                pp.setCallback(mPackageParserCallback);
20622                final PackageParser.Package tmpPkg;
20623                try {
20624                    final @ParseFlags int parseFlags = mDefParseFlags
20625                            | PackageParser.PARSE_MUST_BE_APK
20626                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20627                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20628                } catch (PackageParserException e) {
20629                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20630                    return;
20631                }
20632                synchronized (mInstallLock) {
20633                    // Disable the stub and remove any package entries
20634                    removePackageLI(deletedPkg, true);
20635                    synchronized (mPackages) {
20636                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20637                    }
20638                    final PackageParser.Package pkg;
20639                    try (PackageFreezer freezer =
20640                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20641                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20642                                | PackageParser.PARSE_ENFORCE_CODE;
20643                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20644                                0 /*currentTime*/, null /*user*/);
20645                        prepareAppDataAfterInstallLIF(pkg);
20646                        synchronized (mPackages) {
20647                            try {
20648                                updateSharedLibrariesLPr(pkg, null);
20649                            } catch (PackageManagerException e) {
20650                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20651                            }
20652                            mPermissionManager.updatePermissions(
20653                                    pkg.packageName, pkg, true, mPackages.values(),
20654                                    mPermissionCallback);
20655                            mSettings.writeLPr();
20656                        }
20657                    } catch (PackageManagerException e) {
20658                        // Whoops! Something went wrong; try to roll back to the stub
20659                        Slog.w(TAG, "Failed to install compressed system package:"
20660                                + pkgSetting.name, e);
20661                        // Remove the failed install
20662                        removeCodePathLI(codePath);
20663
20664                        // Install the system package
20665                        try (PackageFreezer freezer =
20666                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20667                            synchronized (mPackages) {
20668                                // NOTE: The system package always needs to be enabled; even
20669                                // if it's for a compressed stub. If we don't, installing the
20670                                // system package fails during scan [scanning checks the disabled
20671                                // packages]. We will reverse this later, after we've "installed"
20672                                // the stub.
20673                                // This leaves us in a fragile state; the stub should never be
20674                                // enabled, so, cross your fingers and hope nothing goes wrong
20675                                // until we can disable the package later.
20676                                enableSystemPackageLPw(deletedPkg);
20677                            }
20678                            installPackageFromSystemLIF(deletedPkg.codePath,
20679                                    false /*isPrivileged*/, null /*allUserHandles*/,
20680                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20681                                    true /*writeSettings*/);
20682                        } catch (PackageManagerException pme) {
20683                            Slog.w(TAG, "Failed to restore system package:"
20684                                    + deletedPkg.packageName, pme);
20685                        } finally {
20686                            synchronized (mPackages) {
20687                                mSettings.disableSystemPackageLPw(
20688                                        deletedPkg.packageName, true /*replaced*/);
20689                                mSettings.writeLPr();
20690                            }
20691                        }
20692                        return;
20693                    }
20694                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20695                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20696                    mDexManager.notifyPackageUpdated(pkg.packageName,
20697                            pkg.baseCodePath, pkg.splitCodePaths);
20698                }
20699            }
20700            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20701                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20702                // Don't care about who enables an app.
20703                callingPackage = null;
20704            }
20705            synchronized (mPackages) {
20706                pkgSetting.setEnabled(newState, userId, callingPackage);
20707            }
20708        } else {
20709            synchronized (mPackages) {
20710                // We're dealing with a component level state change
20711                // First, verify that this is a valid class name.
20712                PackageParser.Package pkg = pkgSetting.pkg;
20713                if (pkg == null || !pkg.hasComponentClassName(className)) {
20714                    if (pkg != null &&
20715                            pkg.applicationInfo.targetSdkVersion >=
20716                                    Build.VERSION_CODES.JELLY_BEAN) {
20717                        throw new IllegalArgumentException("Component class " + className
20718                                + " does not exist in " + packageName);
20719                    } else {
20720                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20721                                + className + " does not exist in " + packageName);
20722                    }
20723                }
20724                switch (newState) {
20725                    case COMPONENT_ENABLED_STATE_ENABLED:
20726                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20727                            return;
20728                        }
20729                        break;
20730                    case COMPONENT_ENABLED_STATE_DISABLED:
20731                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20732                            return;
20733                        }
20734                        break;
20735                    case COMPONENT_ENABLED_STATE_DEFAULT:
20736                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20737                            return;
20738                        }
20739                        break;
20740                    default:
20741                        Slog.e(TAG, "Invalid new component state: " + newState);
20742                        return;
20743                }
20744            }
20745        }
20746        synchronized (mPackages) {
20747            scheduleWritePackageRestrictionsLocked(userId);
20748            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20749            final long callingId = Binder.clearCallingIdentity();
20750            try {
20751                updateInstantAppInstallerLocked(packageName);
20752            } finally {
20753                Binder.restoreCallingIdentity(callingId);
20754            }
20755            components = mPendingBroadcasts.get(userId, packageName);
20756            final boolean newPackage = components == null;
20757            if (newPackage) {
20758                components = new ArrayList<String>();
20759            }
20760            if (!components.contains(componentName)) {
20761                components.add(componentName);
20762            }
20763            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20764                sendNow = true;
20765                // Purge entry from pending broadcast list if another one exists already
20766                // since we are sending one right away.
20767                mPendingBroadcasts.remove(userId, packageName);
20768            } else {
20769                if (newPackage) {
20770                    mPendingBroadcasts.put(userId, packageName, components);
20771                }
20772                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20773                    // Schedule a message
20774                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20775                }
20776            }
20777        }
20778
20779        long callingId = Binder.clearCallingIdentity();
20780        try {
20781            if (sendNow) {
20782                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20783                sendPackageChangedBroadcast(packageName,
20784                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20785            }
20786        } finally {
20787            Binder.restoreCallingIdentity(callingId);
20788        }
20789    }
20790
20791    @Override
20792    public void flushPackageRestrictionsAsUser(int userId) {
20793        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20794            return;
20795        }
20796        if (!sUserManager.exists(userId)) {
20797            return;
20798        }
20799        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20800                false /* checkShell */, "flushPackageRestrictions");
20801        synchronized (mPackages) {
20802            mSettings.writePackageRestrictionsLPr(userId);
20803            mDirtyUsers.remove(userId);
20804            if (mDirtyUsers.isEmpty()) {
20805                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20806            }
20807        }
20808    }
20809
20810    private void sendPackageChangedBroadcast(String packageName,
20811            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20812        if (DEBUG_INSTALL)
20813            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20814                    + componentNames);
20815        Bundle extras = new Bundle(4);
20816        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20817        String nameList[] = new String[componentNames.size()];
20818        componentNames.toArray(nameList);
20819        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20820        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20821        extras.putInt(Intent.EXTRA_UID, packageUid);
20822        // If this is not reporting a change of the overall package, then only send it
20823        // to registered receivers.  We don't want to launch a swath of apps for every
20824        // little component state change.
20825        final int flags = !componentNames.contains(packageName)
20826                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20827        final int userId = UserHandle.getUserId(packageUid);
20828        final boolean isInstantApp = isInstantApp(packageName, userId);
20829        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20830        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20831        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20832                userIds, instantUserIds);
20833    }
20834
20835    @Override
20836    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20837        if (!sUserManager.exists(userId)) return;
20838        final int callingUid = Binder.getCallingUid();
20839        if (getInstantAppPackageName(callingUid) != null) {
20840            return;
20841        }
20842        final int permission = mContext.checkCallingOrSelfPermission(
20843                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20844        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20845        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20846                true /* requireFullPermission */, true /* checkShell */, "stop package");
20847        // writer
20848        synchronized (mPackages) {
20849            final PackageSetting ps = mSettings.mPackages.get(packageName);
20850            if (!filterAppAccessLPr(ps, callingUid, userId)
20851                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20852                            allowedByPermission, callingUid, userId)) {
20853                scheduleWritePackageRestrictionsLocked(userId);
20854            }
20855        }
20856    }
20857
20858    @Override
20859    public String getInstallerPackageName(String packageName) {
20860        final int callingUid = Binder.getCallingUid();
20861        synchronized (mPackages) {
20862            final PackageSetting ps = mSettings.mPackages.get(packageName);
20863            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20864                return null;
20865            }
20866            return mSettings.getInstallerPackageNameLPr(packageName);
20867        }
20868    }
20869
20870    public boolean isOrphaned(String packageName) {
20871        // reader
20872        synchronized (mPackages) {
20873            return mSettings.isOrphaned(packageName);
20874        }
20875    }
20876
20877    @Override
20878    public int getApplicationEnabledSetting(String packageName, int userId) {
20879        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20880        int callingUid = Binder.getCallingUid();
20881        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20882                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20883        // reader
20884        synchronized (mPackages) {
20885            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20886                return COMPONENT_ENABLED_STATE_DISABLED;
20887            }
20888            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20889        }
20890    }
20891
20892    @Override
20893    public int getComponentEnabledSetting(ComponentName component, int userId) {
20894        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20895        int callingUid = Binder.getCallingUid();
20896        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20897                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20898        synchronized (mPackages) {
20899            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20900                    component, TYPE_UNKNOWN, userId)) {
20901                return COMPONENT_ENABLED_STATE_DISABLED;
20902            }
20903            return mSettings.getComponentEnabledSettingLPr(component, userId);
20904        }
20905    }
20906
20907    @Override
20908    public void enterSafeMode() {
20909        enforceSystemOrRoot("Only the system can request entering safe mode");
20910
20911        if (!mSystemReady) {
20912            mSafeMode = true;
20913        }
20914    }
20915
20916    @Override
20917    public void systemReady() {
20918        enforceSystemOrRoot("Only the system can claim the system is ready");
20919
20920        mSystemReady = true;
20921        final ContentResolver resolver = mContext.getContentResolver();
20922        ContentObserver co = new ContentObserver(mHandler) {
20923            @Override
20924            public void onChange(boolean selfChange) {
20925                mWebInstantAppsDisabled =
20926                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20927                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20928            }
20929        };
20930        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20931                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20932                false, co, UserHandle.USER_SYSTEM);
20933        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20934                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20935        co.onChange(true);
20936
20937        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20938        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20939        // it is done.
20940        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20941            @Override
20942            public void onChange(boolean selfChange) {
20943                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20944                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20945                        oobEnabled == 1 ? "true" : "false");
20946            }
20947        };
20948        mContext.getContentResolver().registerContentObserver(
20949                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20950                UserHandle.USER_SYSTEM);
20951        // At boot, restore the value from the setting, which persists across reboot.
20952        privAppOobObserver.onChange(true);
20953
20954        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20955        // disabled after already being started.
20956        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20957                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20958
20959        // Read the compatibilty setting when the system is ready.
20960        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20961                mContext.getContentResolver(),
20962                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20963        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20964        if (DEBUG_SETTINGS) {
20965            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20966        }
20967
20968        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20969
20970        synchronized (mPackages) {
20971            // Verify that all of the preferred activity components actually
20972            // exist.  It is possible for applications to be updated and at
20973            // that point remove a previously declared activity component that
20974            // had been set as a preferred activity.  We try to clean this up
20975            // the next time we encounter that preferred activity, but it is
20976            // possible for the user flow to never be able to return to that
20977            // situation so here we do a sanity check to make sure we haven't
20978            // left any junk around.
20979            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20980            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20981                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20982                removed.clear();
20983                for (PreferredActivity pa : pir.filterSet()) {
20984                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20985                        removed.add(pa);
20986                    }
20987                }
20988                if (removed.size() > 0) {
20989                    for (int r=0; r<removed.size(); r++) {
20990                        PreferredActivity pa = removed.get(r);
20991                        Slog.w(TAG, "Removing dangling preferred activity: "
20992                                + pa.mPref.mComponent);
20993                        pir.removeFilter(pa);
20994                    }
20995                    mSettings.writePackageRestrictionsLPr(
20996                            mSettings.mPreferredActivities.keyAt(i));
20997                }
20998            }
20999
21000            for (int userId : UserManagerService.getInstance().getUserIds()) {
21001                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21002                    grantPermissionsUserIds = ArrayUtils.appendInt(
21003                            grantPermissionsUserIds, userId);
21004                }
21005            }
21006        }
21007        sUserManager.systemReady();
21008        // If we upgraded grant all default permissions before kicking off.
21009        for (int userId : grantPermissionsUserIds) {
21010            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21011        }
21012
21013        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21014            // If we did not grant default permissions, we preload from this the
21015            // default permission exceptions lazily to ensure we don't hit the
21016            // disk on a new user creation.
21017            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21018        }
21019
21020        // Now that we've scanned all packages, and granted any default
21021        // permissions, ensure permissions are updated. Beware of dragons if you
21022        // try optimizing this.
21023        synchronized (mPackages) {
21024            mPermissionManager.updateAllPermissions(
21025                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21026                    mPermissionCallback);
21027        }
21028
21029        // Kick off any messages waiting for system ready
21030        if (mPostSystemReadyMessages != null) {
21031            for (Message msg : mPostSystemReadyMessages) {
21032                msg.sendToTarget();
21033            }
21034            mPostSystemReadyMessages = null;
21035        }
21036
21037        // Watch for external volumes that come and go over time
21038        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21039        storage.registerListener(mStorageListener);
21040
21041        mInstallerService.systemReady();
21042        mPackageDexOptimizer.systemReady();
21043
21044        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21045                StorageManagerInternal.class);
21046        StorageManagerInternal.addExternalStoragePolicy(
21047                new StorageManagerInternal.ExternalStorageMountPolicy() {
21048            @Override
21049            public int getMountMode(int uid, String packageName) {
21050                if (Process.isIsolated(uid)) {
21051                    return Zygote.MOUNT_EXTERNAL_NONE;
21052                }
21053                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21054                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21055                }
21056                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21057                    return Zygote.MOUNT_EXTERNAL_READ;
21058                }
21059                return Zygote.MOUNT_EXTERNAL_WRITE;
21060            }
21061
21062            @Override
21063            public boolean hasExternalStorage(int uid, String packageName) {
21064                return true;
21065            }
21066        });
21067
21068        // Now that we're mostly running, clean up stale users and apps
21069        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21070        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21071
21072        mPermissionManager.systemReady();
21073
21074        if (mInstantAppResolverConnection != null) {
21075            mContext.registerReceiver(new BroadcastReceiver() {
21076                @Override
21077                public void onReceive(Context context, Intent intent) {
21078                    mInstantAppResolverConnection.optimisticBind();
21079                    mContext.unregisterReceiver(this);
21080                }
21081            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21082        }
21083    }
21084
21085    public void waitForAppDataPrepared() {
21086        if (mPrepareAppDataFuture == null) {
21087            return;
21088        }
21089        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21090        mPrepareAppDataFuture = null;
21091    }
21092
21093    @Override
21094    public boolean isSafeMode() {
21095        // allow instant applications
21096        return mSafeMode;
21097    }
21098
21099    @Override
21100    public boolean hasSystemUidErrors() {
21101        // allow instant applications
21102        return mHasSystemUidErrors;
21103    }
21104
21105    static String arrayToString(int[] array) {
21106        StringBuffer buf = new StringBuffer(128);
21107        buf.append('[');
21108        if (array != null) {
21109            for (int i=0; i<array.length; i++) {
21110                if (i > 0) buf.append(", ");
21111                buf.append(array[i]);
21112            }
21113        }
21114        buf.append(']');
21115        return buf.toString();
21116    }
21117
21118    @Override
21119    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21120            FileDescriptor err, String[] args, ShellCallback callback,
21121            ResultReceiver resultReceiver) {
21122        (new PackageManagerShellCommand(this)).exec(
21123                this, in, out, err, args, callback, resultReceiver);
21124    }
21125
21126    @Override
21127    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21128        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21129
21130        DumpState dumpState = new DumpState();
21131        boolean fullPreferred = false;
21132        boolean checkin = false;
21133
21134        String packageName = null;
21135        ArraySet<String> permissionNames = null;
21136
21137        int opti = 0;
21138        while (opti < args.length) {
21139            String opt = args[opti];
21140            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21141                break;
21142            }
21143            opti++;
21144
21145            if ("-a".equals(opt)) {
21146                // Right now we only know how to print all.
21147            } else if ("-h".equals(opt)) {
21148                pw.println("Package manager dump options:");
21149                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21150                pw.println("    --checkin: dump for a checkin");
21151                pw.println("    -f: print details of intent filters");
21152                pw.println("    -h: print this help");
21153                pw.println("  cmd may be one of:");
21154                pw.println("    l[ibraries]: list known shared libraries");
21155                pw.println("    f[eatures]: list device features");
21156                pw.println("    k[eysets]: print known keysets");
21157                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21158                pw.println("    perm[issions]: dump permissions");
21159                pw.println("    permission [name ...]: dump declaration and use of given permission");
21160                pw.println("    pref[erred]: print preferred package settings");
21161                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21162                pw.println("    prov[iders]: dump content providers");
21163                pw.println("    p[ackages]: dump installed packages");
21164                pw.println("    s[hared-users]: dump shared user IDs");
21165                pw.println("    m[essages]: print collected runtime messages");
21166                pw.println("    v[erifiers]: print package verifier info");
21167                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21168                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21169                pw.println("    version: print database version info");
21170                pw.println("    write: write current settings now");
21171                pw.println("    installs: details about install sessions");
21172                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21173                pw.println("    dexopt: dump dexopt state");
21174                pw.println("    compiler-stats: dump compiler statistics");
21175                pw.println("    service-permissions: dump permissions required by services");
21176                pw.println("    <package.name>: info about given package");
21177                return;
21178            } else if ("--checkin".equals(opt)) {
21179                checkin = true;
21180            } else if ("-f".equals(opt)) {
21181                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21182            } else if ("--proto".equals(opt)) {
21183                dumpProto(fd);
21184                return;
21185            } else {
21186                pw.println("Unknown argument: " + opt + "; use -h for help");
21187            }
21188        }
21189
21190        // Is the caller requesting to dump a particular piece of data?
21191        if (opti < args.length) {
21192            String cmd = args[opti];
21193            opti++;
21194            // Is this a package name?
21195            if ("android".equals(cmd) || cmd.contains(".")) {
21196                packageName = cmd;
21197                // When dumping a single package, we always dump all of its
21198                // filter information since the amount of data will be reasonable.
21199                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21200            } else if ("check-permission".equals(cmd)) {
21201                if (opti >= args.length) {
21202                    pw.println("Error: check-permission missing permission argument");
21203                    return;
21204                }
21205                String perm = args[opti];
21206                opti++;
21207                if (opti >= args.length) {
21208                    pw.println("Error: check-permission missing package argument");
21209                    return;
21210                }
21211
21212                String pkg = args[opti];
21213                opti++;
21214                int user = UserHandle.getUserId(Binder.getCallingUid());
21215                if (opti < args.length) {
21216                    try {
21217                        user = Integer.parseInt(args[opti]);
21218                    } catch (NumberFormatException e) {
21219                        pw.println("Error: check-permission user argument is not a number: "
21220                                + args[opti]);
21221                        return;
21222                    }
21223                }
21224
21225                // Normalize package name to handle renamed packages and static libs
21226                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21227
21228                pw.println(checkPermission(perm, pkg, user));
21229                return;
21230            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21231                dumpState.setDump(DumpState.DUMP_LIBS);
21232            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21233                dumpState.setDump(DumpState.DUMP_FEATURES);
21234            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21235                if (opti >= args.length) {
21236                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21237                            | DumpState.DUMP_SERVICE_RESOLVERS
21238                            | DumpState.DUMP_RECEIVER_RESOLVERS
21239                            | DumpState.DUMP_CONTENT_RESOLVERS);
21240                } else {
21241                    while (opti < args.length) {
21242                        String name = args[opti];
21243                        if ("a".equals(name) || "activity".equals(name)) {
21244                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21245                        } else if ("s".equals(name) || "service".equals(name)) {
21246                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21247                        } else if ("r".equals(name) || "receiver".equals(name)) {
21248                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21249                        } else if ("c".equals(name) || "content".equals(name)) {
21250                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21251                        } else {
21252                            pw.println("Error: unknown resolver table type: " + name);
21253                            return;
21254                        }
21255                        opti++;
21256                    }
21257                }
21258            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21259                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21260            } else if ("permission".equals(cmd)) {
21261                if (opti >= args.length) {
21262                    pw.println("Error: permission requires permission name");
21263                    return;
21264                }
21265                permissionNames = new ArraySet<>();
21266                while (opti < args.length) {
21267                    permissionNames.add(args[opti]);
21268                    opti++;
21269                }
21270                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21271                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21272            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21273                dumpState.setDump(DumpState.DUMP_PREFERRED);
21274            } else if ("preferred-xml".equals(cmd)) {
21275                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21276                if (opti < args.length && "--full".equals(args[opti])) {
21277                    fullPreferred = true;
21278                    opti++;
21279                }
21280            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21281                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21282            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21283                dumpState.setDump(DumpState.DUMP_PACKAGES);
21284            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21285                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21286            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21287                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21288            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21289                dumpState.setDump(DumpState.DUMP_MESSAGES);
21290            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21291                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21292            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21293                    || "intent-filter-verifiers".equals(cmd)) {
21294                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21295            } else if ("version".equals(cmd)) {
21296                dumpState.setDump(DumpState.DUMP_VERSION);
21297            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21298                dumpState.setDump(DumpState.DUMP_KEYSETS);
21299            } else if ("installs".equals(cmd)) {
21300                dumpState.setDump(DumpState.DUMP_INSTALLS);
21301            } else if ("frozen".equals(cmd)) {
21302                dumpState.setDump(DumpState.DUMP_FROZEN);
21303            } else if ("volumes".equals(cmd)) {
21304                dumpState.setDump(DumpState.DUMP_VOLUMES);
21305            } else if ("dexopt".equals(cmd)) {
21306                dumpState.setDump(DumpState.DUMP_DEXOPT);
21307            } else if ("compiler-stats".equals(cmd)) {
21308                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21309            } else if ("changes".equals(cmd)) {
21310                dumpState.setDump(DumpState.DUMP_CHANGES);
21311            } else if ("service-permissions".equals(cmd)) {
21312                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21313            } else if ("write".equals(cmd)) {
21314                synchronized (mPackages) {
21315                    mSettings.writeLPr();
21316                    pw.println("Settings written.");
21317                    return;
21318                }
21319            }
21320        }
21321
21322        if (checkin) {
21323            pw.println("vers,1");
21324        }
21325
21326        // reader
21327        synchronized (mPackages) {
21328            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21329                if (!checkin) {
21330                    if (dumpState.onTitlePrinted())
21331                        pw.println();
21332                    pw.println("Database versions:");
21333                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21334                }
21335            }
21336
21337            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21338                if (!checkin) {
21339                    if (dumpState.onTitlePrinted())
21340                        pw.println();
21341                    pw.println("Verifiers:");
21342                    pw.print("  Required: ");
21343                    pw.print(mRequiredVerifierPackage);
21344                    pw.print(" (uid=");
21345                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21346                            UserHandle.USER_SYSTEM));
21347                    pw.println(")");
21348                } else if (mRequiredVerifierPackage != null) {
21349                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21350                    pw.print(",");
21351                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21352                            UserHandle.USER_SYSTEM));
21353                }
21354            }
21355
21356            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21357                    packageName == null) {
21358                if (mIntentFilterVerifierComponent != null) {
21359                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21360                    if (!checkin) {
21361                        if (dumpState.onTitlePrinted())
21362                            pw.println();
21363                        pw.println("Intent Filter Verifier:");
21364                        pw.print("  Using: ");
21365                        pw.print(verifierPackageName);
21366                        pw.print(" (uid=");
21367                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21368                                UserHandle.USER_SYSTEM));
21369                        pw.println(")");
21370                    } else if (verifierPackageName != null) {
21371                        pw.print("ifv,"); pw.print(verifierPackageName);
21372                        pw.print(",");
21373                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21374                                UserHandle.USER_SYSTEM));
21375                    }
21376                } else {
21377                    pw.println();
21378                    pw.println("No Intent Filter Verifier available!");
21379                }
21380            }
21381
21382            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21383                boolean printedHeader = false;
21384                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21385                while (it.hasNext()) {
21386                    String libName = it.next();
21387                    LongSparseArray<SharedLibraryEntry> versionedLib
21388                            = mSharedLibraries.get(libName);
21389                    if (versionedLib == null) {
21390                        continue;
21391                    }
21392                    final int versionCount = versionedLib.size();
21393                    for (int i = 0; i < versionCount; i++) {
21394                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21395                        if (!checkin) {
21396                            if (!printedHeader) {
21397                                if (dumpState.onTitlePrinted())
21398                                    pw.println();
21399                                pw.println("Libraries:");
21400                                printedHeader = true;
21401                            }
21402                            pw.print("  ");
21403                        } else {
21404                            pw.print("lib,");
21405                        }
21406                        pw.print(libEntry.info.getName());
21407                        if (libEntry.info.isStatic()) {
21408                            pw.print(" version=" + libEntry.info.getLongVersion());
21409                        }
21410                        if (!checkin) {
21411                            pw.print(" -> ");
21412                        }
21413                        if (libEntry.path != null) {
21414                            pw.print(" (jar) ");
21415                            pw.print(libEntry.path);
21416                        } else {
21417                            pw.print(" (apk) ");
21418                            pw.print(libEntry.apk);
21419                        }
21420                        pw.println();
21421                    }
21422                }
21423            }
21424
21425            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21426                if (dumpState.onTitlePrinted())
21427                    pw.println();
21428                if (!checkin) {
21429                    pw.println("Features:");
21430                }
21431
21432                synchronized (mAvailableFeatures) {
21433                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21434                        if (checkin) {
21435                            pw.print("feat,");
21436                            pw.print(feat.name);
21437                            pw.print(",");
21438                            pw.println(feat.version);
21439                        } else {
21440                            pw.print("  ");
21441                            pw.print(feat.name);
21442                            if (feat.version > 0) {
21443                                pw.print(" version=");
21444                                pw.print(feat.version);
21445                            }
21446                            pw.println();
21447                        }
21448                    }
21449                }
21450            }
21451
21452            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21453                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21454                        : "Activity Resolver Table:", "  ", packageName,
21455                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21456                    dumpState.setTitlePrinted(true);
21457                }
21458            }
21459            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21460                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21461                        : "Receiver Resolver Table:", "  ", packageName,
21462                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21463                    dumpState.setTitlePrinted(true);
21464                }
21465            }
21466            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21467                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21468                        : "Service Resolver Table:", "  ", packageName,
21469                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21470                    dumpState.setTitlePrinted(true);
21471                }
21472            }
21473            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21474                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21475                        : "Provider Resolver Table:", "  ", packageName,
21476                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21477                    dumpState.setTitlePrinted(true);
21478                }
21479            }
21480
21481            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21482                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21483                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21484                    int user = mSettings.mPreferredActivities.keyAt(i);
21485                    if (pir.dump(pw,
21486                            dumpState.getTitlePrinted()
21487                                ? "\nPreferred Activities User " + user + ":"
21488                                : "Preferred Activities User " + user + ":", "  ",
21489                            packageName, true, false)) {
21490                        dumpState.setTitlePrinted(true);
21491                    }
21492                }
21493            }
21494
21495            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21496                pw.flush();
21497                FileOutputStream fout = new FileOutputStream(fd);
21498                BufferedOutputStream str = new BufferedOutputStream(fout);
21499                XmlSerializer serializer = new FastXmlSerializer();
21500                try {
21501                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21502                    serializer.startDocument(null, true);
21503                    serializer.setFeature(
21504                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21505                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21506                    serializer.endDocument();
21507                    serializer.flush();
21508                } catch (IllegalArgumentException e) {
21509                    pw.println("Failed writing: " + e);
21510                } catch (IllegalStateException e) {
21511                    pw.println("Failed writing: " + e);
21512                } catch (IOException e) {
21513                    pw.println("Failed writing: " + e);
21514                }
21515            }
21516
21517            if (!checkin
21518                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21519                    && packageName == null) {
21520                pw.println();
21521                int count = mSettings.mPackages.size();
21522                if (count == 0) {
21523                    pw.println("No applications!");
21524                    pw.println();
21525                } else {
21526                    final String prefix = "  ";
21527                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21528                    if (allPackageSettings.size() == 0) {
21529                        pw.println("No domain preferred apps!");
21530                        pw.println();
21531                    } else {
21532                        pw.println("App verification status:");
21533                        pw.println();
21534                        count = 0;
21535                        for (PackageSetting ps : allPackageSettings) {
21536                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21537                            if (ivi == null || ivi.getPackageName() == null) continue;
21538                            pw.println(prefix + "Package: " + ivi.getPackageName());
21539                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21540                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21541                            pw.println();
21542                            count++;
21543                        }
21544                        if (count == 0) {
21545                            pw.println(prefix + "No app verification established.");
21546                            pw.println();
21547                        }
21548                        for (int userId : sUserManager.getUserIds()) {
21549                            pw.println("App linkages for user " + userId + ":");
21550                            pw.println();
21551                            count = 0;
21552                            for (PackageSetting ps : allPackageSettings) {
21553                                final long status = ps.getDomainVerificationStatusForUser(userId);
21554                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21555                                        && !DEBUG_DOMAIN_VERIFICATION) {
21556                                    continue;
21557                                }
21558                                pw.println(prefix + "Package: " + ps.name);
21559                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21560                                String statusStr = IntentFilterVerificationInfo.
21561                                        getStatusStringFromValue(status);
21562                                pw.println(prefix + "Status:  " + statusStr);
21563                                pw.println();
21564                                count++;
21565                            }
21566                            if (count == 0) {
21567                                pw.println(prefix + "No configured app linkages.");
21568                                pw.println();
21569                            }
21570                        }
21571                    }
21572                }
21573            }
21574
21575            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21576                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21577            }
21578
21579            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21580                boolean printedSomething = false;
21581                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21582                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21583                        continue;
21584                    }
21585                    if (!printedSomething) {
21586                        if (dumpState.onTitlePrinted())
21587                            pw.println();
21588                        pw.println("Registered ContentProviders:");
21589                        printedSomething = true;
21590                    }
21591                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21592                    pw.print("    "); pw.println(p.toString());
21593                }
21594                printedSomething = false;
21595                for (Map.Entry<String, PackageParser.Provider> entry :
21596                        mProvidersByAuthority.entrySet()) {
21597                    PackageParser.Provider p = entry.getValue();
21598                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21599                        continue;
21600                    }
21601                    if (!printedSomething) {
21602                        if (dumpState.onTitlePrinted())
21603                            pw.println();
21604                        pw.println("ContentProvider Authorities:");
21605                        printedSomething = true;
21606                    }
21607                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21608                    pw.print("    "); pw.println(p.toString());
21609                    if (p.info != null && p.info.applicationInfo != null) {
21610                        final String appInfo = p.info.applicationInfo.toString();
21611                        pw.print("      applicationInfo="); pw.println(appInfo);
21612                    }
21613                }
21614            }
21615
21616            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21617                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21618            }
21619
21620            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21621                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21622            }
21623
21624            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21625                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21626            }
21627
21628            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21629                if (dumpState.onTitlePrinted()) pw.println();
21630                pw.println("Package Changes:");
21631                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21632                final int K = mChangedPackages.size();
21633                for (int i = 0; i < K; i++) {
21634                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21635                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21636                    final int N = changes.size();
21637                    if (N == 0) {
21638                        pw.print("    "); pw.println("No packages changed");
21639                    } else {
21640                        for (int j = 0; j < N; j++) {
21641                            final String pkgName = changes.valueAt(j);
21642                            final int sequenceNumber = changes.keyAt(j);
21643                            pw.print("    ");
21644                            pw.print("seq=");
21645                            pw.print(sequenceNumber);
21646                            pw.print(", package=");
21647                            pw.println(pkgName);
21648                        }
21649                    }
21650                }
21651            }
21652
21653            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21654                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21655            }
21656
21657            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21658                // XXX should handle packageName != null by dumping only install data that
21659                // the given package is involved with.
21660                if (dumpState.onTitlePrinted()) pw.println();
21661
21662                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21663                ipw.println();
21664                ipw.println("Frozen packages:");
21665                ipw.increaseIndent();
21666                if (mFrozenPackages.size() == 0) {
21667                    ipw.println("(none)");
21668                } else {
21669                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21670                        ipw.println(mFrozenPackages.valueAt(i));
21671                    }
21672                }
21673                ipw.decreaseIndent();
21674            }
21675
21676            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21677                if (dumpState.onTitlePrinted()) pw.println();
21678
21679                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21680                ipw.println();
21681                ipw.println("Loaded volumes:");
21682                ipw.increaseIndent();
21683                if (mLoadedVolumes.size() == 0) {
21684                    ipw.println("(none)");
21685                } else {
21686                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21687                        ipw.println(mLoadedVolumes.valueAt(i));
21688                    }
21689                }
21690                ipw.decreaseIndent();
21691            }
21692
21693            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21694                    && packageName == null) {
21695                if (dumpState.onTitlePrinted()) pw.println();
21696                pw.println("Service permissions:");
21697
21698                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21699                while (filterIterator.hasNext()) {
21700                    final ServiceIntentInfo info = filterIterator.next();
21701                    final ServiceInfo serviceInfo = info.service.info;
21702                    final String permission = serviceInfo.permission;
21703                    if (permission != null) {
21704                        pw.print("    ");
21705                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21706                        pw.print(": ");
21707                        pw.println(permission);
21708                    }
21709                }
21710            }
21711
21712            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21713                if (dumpState.onTitlePrinted()) pw.println();
21714                dumpDexoptStateLPr(pw, packageName);
21715            }
21716
21717            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21718                if (dumpState.onTitlePrinted()) pw.println();
21719                dumpCompilerStatsLPr(pw, packageName);
21720            }
21721
21722            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21723                if (dumpState.onTitlePrinted()) pw.println();
21724                mSettings.dumpReadMessagesLPr(pw, dumpState);
21725
21726                pw.println();
21727                pw.println("Package warning messages:");
21728                dumpCriticalInfo(pw, null);
21729            }
21730
21731            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21732                dumpCriticalInfo(pw, "msg,");
21733            }
21734        }
21735
21736        // PackageInstaller should be called outside of mPackages lock
21737        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21738            // XXX should handle packageName != null by dumping only install data that
21739            // the given package is involved with.
21740            if (dumpState.onTitlePrinted()) pw.println();
21741            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21742        }
21743    }
21744
21745    private void dumpProto(FileDescriptor fd) {
21746        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21747
21748        synchronized (mPackages) {
21749            final long requiredVerifierPackageToken =
21750                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21751            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21752            proto.write(
21753                    PackageServiceDumpProto.PackageShortProto.UID,
21754                    getPackageUid(
21755                            mRequiredVerifierPackage,
21756                            MATCH_DEBUG_TRIAGED_MISSING,
21757                            UserHandle.USER_SYSTEM));
21758            proto.end(requiredVerifierPackageToken);
21759
21760            if (mIntentFilterVerifierComponent != null) {
21761                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21762                final long verifierPackageToken =
21763                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21764                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21765                proto.write(
21766                        PackageServiceDumpProto.PackageShortProto.UID,
21767                        getPackageUid(
21768                                verifierPackageName,
21769                                MATCH_DEBUG_TRIAGED_MISSING,
21770                                UserHandle.USER_SYSTEM));
21771                proto.end(verifierPackageToken);
21772            }
21773
21774            dumpSharedLibrariesProto(proto);
21775            dumpFeaturesProto(proto);
21776            mSettings.dumpPackagesProto(proto);
21777            mSettings.dumpSharedUsersProto(proto);
21778            dumpCriticalInfo(proto);
21779        }
21780        proto.flush();
21781    }
21782
21783    private void dumpFeaturesProto(ProtoOutputStream proto) {
21784        synchronized (mAvailableFeatures) {
21785            final int count = mAvailableFeatures.size();
21786            for (int i = 0; i < count; i++) {
21787                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21788            }
21789        }
21790    }
21791
21792    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21793        final int count = mSharedLibraries.size();
21794        for (int i = 0; i < count; i++) {
21795            final String libName = mSharedLibraries.keyAt(i);
21796            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21797            if (versionedLib == null) {
21798                continue;
21799            }
21800            final int versionCount = versionedLib.size();
21801            for (int j = 0; j < versionCount; j++) {
21802                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21803                final long sharedLibraryToken =
21804                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21805                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21806                final boolean isJar = (libEntry.path != null);
21807                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21808                if (isJar) {
21809                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21810                } else {
21811                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21812                }
21813                proto.end(sharedLibraryToken);
21814            }
21815        }
21816    }
21817
21818    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21819        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21820        ipw.println();
21821        ipw.println("Dexopt state:");
21822        ipw.increaseIndent();
21823        Collection<PackageParser.Package> packages = null;
21824        if (packageName != null) {
21825            PackageParser.Package targetPackage = mPackages.get(packageName);
21826            if (targetPackage != null) {
21827                packages = Collections.singletonList(targetPackage);
21828            } else {
21829                ipw.println("Unable to find package: " + packageName);
21830                return;
21831            }
21832        } else {
21833            packages = mPackages.values();
21834        }
21835
21836        for (PackageParser.Package pkg : packages) {
21837            ipw.println("[" + pkg.packageName + "]");
21838            ipw.increaseIndent();
21839            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21840                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21841            ipw.decreaseIndent();
21842        }
21843    }
21844
21845    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21846        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21847        ipw.println();
21848        ipw.println("Compiler stats:");
21849        ipw.increaseIndent();
21850        Collection<PackageParser.Package> packages = null;
21851        if (packageName != null) {
21852            PackageParser.Package targetPackage = mPackages.get(packageName);
21853            if (targetPackage != null) {
21854                packages = Collections.singletonList(targetPackage);
21855            } else {
21856                ipw.println("Unable to find package: " + packageName);
21857                return;
21858            }
21859        } else {
21860            packages = mPackages.values();
21861        }
21862
21863        for (PackageParser.Package pkg : packages) {
21864            ipw.println("[" + pkg.packageName + "]");
21865            ipw.increaseIndent();
21866
21867            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21868            if (stats == null) {
21869                ipw.println("(No recorded stats)");
21870            } else {
21871                stats.dump(ipw);
21872            }
21873            ipw.decreaseIndent();
21874        }
21875    }
21876
21877    private String dumpDomainString(String packageName) {
21878        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21879                .getList();
21880        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21881
21882        ArraySet<String> result = new ArraySet<>();
21883        if (iviList.size() > 0) {
21884            for (IntentFilterVerificationInfo ivi : iviList) {
21885                for (String host : ivi.getDomains()) {
21886                    result.add(host);
21887                }
21888            }
21889        }
21890        if (filters != null && filters.size() > 0) {
21891            for (IntentFilter filter : filters) {
21892                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21893                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21894                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21895                    result.addAll(filter.getHostsList());
21896                }
21897            }
21898        }
21899
21900        StringBuilder sb = new StringBuilder(result.size() * 16);
21901        for (String domain : result) {
21902            if (sb.length() > 0) sb.append(" ");
21903            sb.append(domain);
21904        }
21905        return sb.toString();
21906    }
21907
21908    // ------- apps on sdcard specific code -------
21909    static final boolean DEBUG_SD_INSTALL = false;
21910
21911    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21912
21913    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21914
21915    private boolean mMediaMounted = false;
21916
21917    static String getEncryptKey() {
21918        try {
21919            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21920                    SD_ENCRYPTION_KEYSTORE_NAME);
21921            if (sdEncKey == null) {
21922                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21923                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21924                if (sdEncKey == null) {
21925                    Slog.e(TAG, "Failed to create encryption keys");
21926                    return null;
21927                }
21928            }
21929            return sdEncKey;
21930        } catch (NoSuchAlgorithmException nsae) {
21931            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21932            return null;
21933        } catch (IOException ioe) {
21934            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21935            return null;
21936        }
21937    }
21938
21939    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21940            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21941        final int size = infos.size();
21942        final String[] packageNames = new String[size];
21943        final int[] packageUids = new int[size];
21944        for (int i = 0; i < size; i++) {
21945            final ApplicationInfo info = infos.get(i);
21946            packageNames[i] = info.packageName;
21947            packageUids[i] = info.uid;
21948        }
21949        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21950                finishedReceiver);
21951    }
21952
21953    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21954            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21955        sendResourcesChangedBroadcast(mediaStatus, replacing,
21956                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21957    }
21958
21959    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21960            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21961        int size = pkgList.length;
21962        if (size > 0) {
21963            // Send broadcasts here
21964            Bundle extras = new Bundle();
21965            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21966            if (uidArr != null) {
21967                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21968            }
21969            if (replacing) {
21970                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21971            }
21972            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21973                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21974            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21975        }
21976    }
21977
21978    private void loadPrivatePackages(final VolumeInfo vol) {
21979        mHandler.post(new Runnable() {
21980            @Override
21981            public void run() {
21982                loadPrivatePackagesInner(vol);
21983            }
21984        });
21985    }
21986
21987    private void loadPrivatePackagesInner(VolumeInfo vol) {
21988        final String volumeUuid = vol.fsUuid;
21989        if (TextUtils.isEmpty(volumeUuid)) {
21990            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21991            return;
21992        }
21993
21994        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21995        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21996        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21997
21998        final VersionInfo ver;
21999        final List<PackageSetting> packages;
22000        synchronized (mPackages) {
22001            ver = mSettings.findOrCreateVersion(volumeUuid);
22002            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22003        }
22004
22005        for (PackageSetting ps : packages) {
22006            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22007            synchronized (mInstallLock) {
22008                final PackageParser.Package pkg;
22009                try {
22010                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22011                    loaded.add(pkg.applicationInfo);
22012
22013                } catch (PackageManagerException e) {
22014                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22015                }
22016
22017                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22018                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22019                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22020                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22021                }
22022            }
22023        }
22024
22025        // Reconcile app data for all started/unlocked users
22026        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22027        final UserManager um = mContext.getSystemService(UserManager.class);
22028        UserManagerInternal umInternal = getUserManagerInternal();
22029        for (UserInfo user : um.getUsers()) {
22030            final int flags;
22031            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22032                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22033            } else if (umInternal.isUserRunning(user.id)) {
22034                flags = StorageManager.FLAG_STORAGE_DE;
22035            } else {
22036                continue;
22037            }
22038
22039            try {
22040                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22041                synchronized (mInstallLock) {
22042                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22043                }
22044            } catch (IllegalStateException e) {
22045                // Device was probably ejected, and we'll process that event momentarily
22046                Slog.w(TAG, "Failed to prepare storage: " + e);
22047            }
22048        }
22049
22050        synchronized (mPackages) {
22051            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22052            if (sdkUpdated) {
22053                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22054                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22055            }
22056            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22057                    mPermissionCallback);
22058
22059            // Yay, everything is now upgraded
22060            ver.forceCurrent();
22061
22062            mSettings.writeLPr();
22063        }
22064
22065        for (PackageFreezer freezer : freezers) {
22066            freezer.close();
22067        }
22068
22069        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22070        sendResourcesChangedBroadcast(true, false, loaded, null);
22071        mLoadedVolumes.add(vol.getId());
22072    }
22073
22074    private void unloadPrivatePackages(final VolumeInfo vol) {
22075        mHandler.post(new Runnable() {
22076            @Override
22077            public void run() {
22078                unloadPrivatePackagesInner(vol);
22079            }
22080        });
22081    }
22082
22083    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22084        final String volumeUuid = vol.fsUuid;
22085        if (TextUtils.isEmpty(volumeUuid)) {
22086            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22087            return;
22088        }
22089
22090        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22091        synchronized (mInstallLock) {
22092        synchronized (mPackages) {
22093            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22094            for (PackageSetting ps : packages) {
22095                if (ps.pkg == null) continue;
22096
22097                final ApplicationInfo info = ps.pkg.applicationInfo;
22098                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22099                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22100
22101                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22102                        "unloadPrivatePackagesInner")) {
22103                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22104                            false, null)) {
22105                        unloaded.add(info);
22106                    } else {
22107                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22108                    }
22109                }
22110
22111                // Try very hard to release any references to this package
22112                // so we don't risk the system server being killed due to
22113                // open FDs
22114                AttributeCache.instance().removePackage(ps.name);
22115            }
22116
22117            mSettings.writeLPr();
22118        }
22119        }
22120
22121        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22122        sendResourcesChangedBroadcast(false, false, unloaded, null);
22123        mLoadedVolumes.remove(vol.getId());
22124
22125        // Try very hard to release any references to this path so we don't risk
22126        // the system server being killed due to open FDs
22127        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22128
22129        for (int i = 0; i < 3; i++) {
22130            System.gc();
22131            System.runFinalization();
22132        }
22133    }
22134
22135    private void assertPackageKnown(String volumeUuid, String packageName)
22136            throws PackageManagerException {
22137        synchronized (mPackages) {
22138            // Normalize package name to handle renamed packages
22139            packageName = normalizePackageNameLPr(packageName);
22140
22141            final PackageSetting ps = mSettings.mPackages.get(packageName);
22142            if (ps == null) {
22143                throw new PackageManagerException("Package " + packageName + " is unknown");
22144            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22145                throw new PackageManagerException(
22146                        "Package " + packageName + " found on unknown volume " + volumeUuid
22147                                + "; expected volume " + ps.volumeUuid);
22148            }
22149        }
22150    }
22151
22152    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22153            throws PackageManagerException {
22154        synchronized (mPackages) {
22155            // Normalize package name to handle renamed packages
22156            packageName = normalizePackageNameLPr(packageName);
22157
22158            final PackageSetting ps = mSettings.mPackages.get(packageName);
22159            if (ps == null) {
22160                throw new PackageManagerException("Package " + packageName + " is unknown");
22161            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22162                throw new PackageManagerException(
22163                        "Package " + packageName + " found on unknown volume " + volumeUuid
22164                                + "; expected volume " + ps.volumeUuid);
22165            } else if (!ps.getInstalled(userId)) {
22166                throw new PackageManagerException(
22167                        "Package " + packageName + " not installed for user " + userId);
22168            }
22169        }
22170    }
22171
22172    private List<String> collectAbsoluteCodePaths() {
22173        synchronized (mPackages) {
22174            List<String> codePaths = new ArrayList<>();
22175            final int packageCount = mSettings.mPackages.size();
22176            for (int i = 0; i < packageCount; i++) {
22177                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22178                codePaths.add(ps.codePath.getAbsolutePath());
22179            }
22180            return codePaths;
22181        }
22182    }
22183
22184    /**
22185     * Examine all apps present on given mounted volume, and destroy apps that
22186     * aren't expected, either due to uninstallation or reinstallation on
22187     * another volume.
22188     */
22189    private void reconcileApps(String volumeUuid) {
22190        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22191        List<File> filesToDelete = null;
22192
22193        final File[] files = FileUtils.listFilesOrEmpty(
22194                Environment.getDataAppDirectory(volumeUuid));
22195        for (File file : files) {
22196            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22197                    && !PackageInstallerService.isStageName(file.getName());
22198            if (!isPackage) {
22199                // Ignore entries which are not packages
22200                continue;
22201            }
22202
22203            String absolutePath = file.getAbsolutePath();
22204
22205            boolean pathValid = false;
22206            final int absoluteCodePathCount = absoluteCodePaths.size();
22207            for (int i = 0; i < absoluteCodePathCount; i++) {
22208                String absoluteCodePath = absoluteCodePaths.get(i);
22209                if (absolutePath.startsWith(absoluteCodePath)) {
22210                    pathValid = true;
22211                    break;
22212                }
22213            }
22214
22215            if (!pathValid) {
22216                if (filesToDelete == null) {
22217                    filesToDelete = new ArrayList<>();
22218                }
22219                filesToDelete.add(file);
22220            }
22221        }
22222
22223        if (filesToDelete != null) {
22224            final int fileToDeleteCount = filesToDelete.size();
22225            for (int i = 0; i < fileToDeleteCount; i++) {
22226                File fileToDelete = filesToDelete.get(i);
22227                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22228                synchronized (mInstallLock) {
22229                    removeCodePathLI(fileToDelete);
22230                }
22231            }
22232        }
22233    }
22234
22235    /**
22236     * Reconcile all app data for the given user.
22237     * <p>
22238     * Verifies that directories exist and that ownership and labeling is
22239     * correct for all installed apps on all mounted volumes.
22240     */
22241    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22242        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22243        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22244            final String volumeUuid = vol.getFsUuid();
22245            synchronized (mInstallLock) {
22246                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22247            }
22248        }
22249    }
22250
22251    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22252            boolean migrateAppData) {
22253        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22254    }
22255
22256    /**
22257     * Reconcile all app data on given mounted volume.
22258     * <p>
22259     * Destroys app data that isn't expected, either due to uninstallation or
22260     * reinstallation on another volume.
22261     * <p>
22262     * Verifies that directories exist and that ownership and labeling is
22263     * correct for all installed apps.
22264     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22265     */
22266    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22267            boolean migrateAppData, boolean onlyCoreApps) {
22268        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22269                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22270        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22271
22272        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22273        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22274
22275        // First look for stale data that doesn't belong, and check if things
22276        // have changed since we did our last restorecon
22277        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22278            if (StorageManager.isFileEncryptedNativeOrEmulated()
22279                    && !StorageManager.isUserKeyUnlocked(userId)) {
22280                throw new RuntimeException(
22281                        "Yikes, someone asked us to reconcile CE storage while " + userId
22282                                + " was still locked; this would have caused massive data loss!");
22283            }
22284
22285            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22286            for (File file : files) {
22287                final String packageName = file.getName();
22288                try {
22289                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22290                } catch (PackageManagerException e) {
22291                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22292                    try {
22293                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22294                                StorageManager.FLAG_STORAGE_CE, 0);
22295                    } catch (InstallerException e2) {
22296                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22297                    }
22298                }
22299            }
22300        }
22301        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22302            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22303            for (File file : files) {
22304                final String packageName = file.getName();
22305                try {
22306                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22307                } catch (PackageManagerException e) {
22308                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22309                    try {
22310                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22311                                StorageManager.FLAG_STORAGE_DE, 0);
22312                    } catch (InstallerException e2) {
22313                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22314                    }
22315                }
22316            }
22317        }
22318
22319        // Ensure that data directories are ready to roll for all packages
22320        // installed for this volume and user
22321        final List<PackageSetting> packages;
22322        synchronized (mPackages) {
22323            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22324        }
22325        int preparedCount = 0;
22326        for (PackageSetting ps : packages) {
22327            final String packageName = ps.name;
22328            if (ps.pkg == null) {
22329                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22330                // TODO: might be due to legacy ASEC apps; we should circle back
22331                // and reconcile again once they're scanned
22332                continue;
22333            }
22334            // Skip non-core apps if requested
22335            if (onlyCoreApps && !ps.pkg.coreApp) {
22336                result.add(packageName);
22337                continue;
22338            }
22339
22340            if (ps.getInstalled(userId)) {
22341                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22342                preparedCount++;
22343            }
22344        }
22345
22346        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22347        return result;
22348    }
22349
22350    /**
22351     * Prepare app data for the given app just after it was installed or
22352     * upgraded. This method carefully only touches users that it's installed
22353     * for, and it forces a restorecon to handle any seinfo changes.
22354     * <p>
22355     * Verifies that directories exist and that ownership and labeling is
22356     * correct for all installed apps. If there is an ownership mismatch, it
22357     * will try recovering system apps by wiping data; third-party app data is
22358     * left intact.
22359     * <p>
22360     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22361     */
22362    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22363        final PackageSetting ps;
22364        synchronized (mPackages) {
22365            ps = mSettings.mPackages.get(pkg.packageName);
22366            mSettings.writeKernelMappingLPr(ps);
22367        }
22368
22369        final UserManager um = mContext.getSystemService(UserManager.class);
22370        UserManagerInternal umInternal = getUserManagerInternal();
22371        for (UserInfo user : um.getUsers()) {
22372            final int flags;
22373            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22374                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22375            } else if (umInternal.isUserRunning(user.id)) {
22376                flags = StorageManager.FLAG_STORAGE_DE;
22377            } else {
22378                continue;
22379            }
22380
22381            if (ps.getInstalled(user.id)) {
22382                // TODO: when user data is locked, mark that we're still dirty
22383                prepareAppDataLIF(pkg, user.id, flags);
22384            }
22385        }
22386    }
22387
22388    /**
22389     * Prepare app data for the given app.
22390     * <p>
22391     * Verifies that directories exist and that ownership and labeling is
22392     * correct for all installed apps. If there is an ownership mismatch, this
22393     * will try recovering system apps by wiping data; third-party app data is
22394     * left intact.
22395     */
22396    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22397        if (pkg == null) {
22398            Slog.wtf(TAG, "Package was null!", new Throwable());
22399            return;
22400        }
22401        prepareAppDataLeafLIF(pkg, userId, flags);
22402        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22403        for (int i = 0; i < childCount; i++) {
22404            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22405        }
22406    }
22407
22408    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22409            boolean maybeMigrateAppData) {
22410        prepareAppDataLIF(pkg, userId, flags);
22411
22412        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22413            // We may have just shuffled around app data directories, so
22414            // prepare them one more time
22415            prepareAppDataLIF(pkg, userId, flags);
22416        }
22417    }
22418
22419    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22420        if (DEBUG_APP_DATA) {
22421            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22422                    + Integer.toHexString(flags));
22423        }
22424
22425        final PackageSetting ps;
22426        synchronized (mPackages) {
22427            ps = mSettings.mPackages.get(pkg.packageName);
22428        }
22429        final String volumeUuid = pkg.volumeUuid;
22430        final String packageName = pkg.packageName;
22431        final ApplicationInfo app = (ps == null)
22432                ? pkg.applicationInfo
22433                : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
22434
22435        final int appId = UserHandle.getAppId(app.uid);
22436
22437        Preconditions.checkNotNull(app.seInfo);
22438
22439        final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
22440        long ceDataInode = -1;
22441        try {
22442            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22443                    appId, seInfo, app.targetSdkVersion);
22444        } catch (InstallerException e) {
22445            if (app.isSystemApp()) {
22446                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22447                        + ", but trying to recover: " + e);
22448                destroyAppDataLeafLIF(pkg, userId, flags);
22449                try {
22450                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22451                            appId, seInfo, app.targetSdkVersion);
22452                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22453                } catch (InstallerException e2) {
22454                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22455                }
22456            } else {
22457                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22458            }
22459        }
22460        // Prepare the application profiles only for upgrades and first boot (so that we don't
22461        // repeat the same operation at each boot).
22462        // We only have to cover the upgrade and first boot here because for app installs we
22463        // prepare the profiles before invoking dexopt (in installPackageLI).
22464        //
22465        // We also have to cover non system users because we do not call the usual install package
22466        // methods for them.
22467        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22468            mArtManagerService.prepareAppProfiles(pkg, userId);
22469        }
22470
22471        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22472            // TODO: mark this structure as dirty so we persist it!
22473            synchronized (mPackages) {
22474                if (ps != null) {
22475                    ps.setCeDataInode(ceDataInode, userId);
22476                }
22477            }
22478        }
22479
22480        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22481    }
22482
22483    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22484        if (pkg == null) {
22485            Slog.wtf(TAG, "Package was null!", new Throwable());
22486            return;
22487        }
22488        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22489        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22490        for (int i = 0; i < childCount; i++) {
22491            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22492        }
22493    }
22494
22495    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22496        final String volumeUuid = pkg.volumeUuid;
22497        final String packageName = pkg.packageName;
22498        final ApplicationInfo app = pkg.applicationInfo;
22499
22500        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22501            // Create a native library symlink only if we have native libraries
22502            // and if the native libraries are 32 bit libraries. We do not provide
22503            // this symlink for 64 bit libraries.
22504            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22505                final String nativeLibPath = app.nativeLibraryDir;
22506                try {
22507                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22508                            nativeLibPath, userId);
22509                } catch (InstallerException e) {
22510                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22511                }
22512            }
22513        }
22514    }
22515
22516    /**
22517     * For system apps on non-FBE devices, this method migrates any existing
22518     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22519     * requested by the app.
22520     */
22521    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22522        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22523                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22524            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22525                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22526            try {
22527                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22528                        storageTarget);
22529            } catch (InstallerException e) {
22530                logCriticalInfo(Log.WARN,
22531                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22532            }
22533            return true;
22534        } else {
22535            return false;
22536        }
22537    }
22538
22539    public PackageFreezer freezePackage(String packageName, String killReason) {
22540        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22541    }
22542
22543    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22544        return new PackageFreezer(packageName, userId, killReason);
22545    }
22546
22547    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22548            String killReason) {
22549        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22550    }
22551
22552    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22553            String killReason) {
22554        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22555            return new PackageFreezer();
22556        } else {
22557            return freezePackage(packageName, userId, killReason);
22558        }
22559    }
22560
22561    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22562            String killReason) {
22563        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22564    }
22565
22566    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22567            String killReason) {
22568        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22569            return new PackageFreezer();
22570        } else {
22571            return freezePackage(packageName, userId, killReason);
22572        }
22573    }
22574
22575    /**
22576     * Class that freezes and kills the given package upon creation, and
22577     * unfreezes it upon closing. This is typically used when doing surgery on
22578     * app code/data to prevent the app from running while you're working.
22579     */
22580    private class PackageFreezer implements AutoCloseable {
22581        private final String mPackageName;
22582        private final PackageFreezer[] mChildren;
22583
22584        private final boolean mWeFroze;
22585
22586        private final AtomicBoolean mClosed = new AtomicBoolean();
22587        private final CloseGuard mCloseGuard = CloseGuard.get();
22588
22589        /**
22590         * Create and return a stub freezer that doesn't actually do anything,
22591         * typically used when someone requested
22592         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22593         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22594         */
22595        public PackageFreezer() {
22596            mPackageName = null;
22597            mChildren = null;
22598            mWeFroze = false;
22599            mCloseGuard.open("close");
22600        }
22601
22602        public PackageFreezer(String packageName, int userId, String killReason) {
22603            synchronized (mPackages) {
22604                mPackageName = packageName;
22605                mWeFroze = mFrozenPackages.add(mPackageName);
22606
22607                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22608                if (ps != null) {
22609                    killApplication(ps.name, ps.appId, userId, killReason);
22610                }
22611
22612                final PackageParser.Package p = mPackages.get(packageName);
22613                if (p != null && p.childPackages != null) {
22614                    final int N = p.childPackages.size();
22615                    mChildren = new PackageFreezer[N];
22616                    for (int i = 0; i < N; i++) {
22617                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22618                                userId, killReason);
22619                    }
22620                } else {
22621                    mChildren = null;
22622                }
22623            }
22624            mCloseGuard.open("close");
22625        }
22626
22627        @Override
22628        protected void finalize() throws Throwable {
22629            try {
22630                if (mCloseGuard != null) {
22631                    mCloseGuard.warnIfOpen();
22632                }
22633
22634                close();
22635            } finally {
22636                super.finalize();
22637            }
22638        }
22639
22640        @Override
22641        public void close() {
22642            mCloseGuard.close();
22643            if (mClosed.compareAndSet(false, true)) {
22644                synchronized (mPackages) {
22645                    if (mWeFroze) {
22646                        mFrozenPackages.remove(mPackageName);
22647                    }
22648
22649                    if (mChildren != null) {
22650                        for (PackageFreezer freezer : mChildren) {
22651                            freezer.close();
22652                        }
22653                    }
22654                }
22655            }
22656        }
22657    }
22658
22659    /**
22660     * Verify that given package is currently frozen.
22661     */
22662    private void checkPackageFrozen(String packageName) {
22663        synchronized (mPackages) {
22664            if (!mFrozenPackages.contains(packageName)) {
22665                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22666            }
22667        }
22668    }
22669
22670    @Override
22671    public int movePackage(final String packageName, final String volumeUuid) {
22672        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22673
22674        final int callingUid = Binder.getCallingUid();
22675        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22676        final int moveId = mNextMoveId.getAndIncrement();
22677        mHandler.post(new Runnable() {
22678            @Override
22679            public void run() {
22680                try {
22681                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22682                } catch (PackageManagerException e) {
22683                    Slog.w(TAG, "Failed to move " + packageName, e);
22684                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22685                }
22686            }
22687        });
22688        return moveId;
22689    }
22690
22691    private void movePackageInternal(final String packageName, final String volumeUuid,
22692            final int moveId, final int callingUid, UserHandle user)
22693                    throws PackageManagerException {
22694        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22695        final PackageManager pm = mContext.getPackageManager();
22696
22697        final boolean currentAsec;
22698        final String currentVolumeUuid;
22699        final File codeFile;
22700        final String installerPackageName;
22701        final String packageAbiOverride;
22702        final int appId;
22703        final String seinfo;
22704        final String label;
22705        final int targetSdkVersion;
22706        final PackageFreezer freezer;
22707        final int[] installedUserIds;
22708
22709        // reader
22710        synchronized (mPackages) {
22711            final PackageParser.Package pkg = mPackages.get(packageName);
22712            final PackageSetting ps = mSettings.mPackages.get(packageName);
22713            if (pkg == null
22714                    || ps == null
22715                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22716                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22717            }
22718            if (pkg.applicationInfo.isSystemApp()) {
22719                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22720                        "Cannot move system application");
22721            }
22722
22723            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22724            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22725                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22726            if (isInternalStorage && !allow3rdPartyOnInternal) {
22727                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22728                        "3rd party apps are not allowed on internal storage");
22729            }
22730
22731            if (pkg.applicationInfo.isExternalAsec()) {
22732                currentAsec = true;
22733                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22734            } else if (pkg.applicationInfo.isForwardLocked()) {
22735                currentAsec = true;
22736                currentVolumeUuid = "forward_locked";
22737            } else {
22738                currentAsec = false;
22739                currentVolumeUuid = ps.volumeUuid;
22740
22741                final File probe = new File(pkg.codePath);
22742                final File probeOat = new File(probe, "oat");
22743                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22744                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22745                            "Move only supported for modern cluster style installs");
22746                }
22747            }
22748
22749            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22750                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22751                        "Package already moved to " + volumeUuid);
22752            }
22753            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22754                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22755                        "Device admin cannot be moved");
22756            }
22757
22758            if (mFrozenPackages.contains(packageName)) {
22759                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22760                        "Failed to move already frozen package");
22761            }
22762
22763            codeFile = new File(pkg.codePath);
22764            installerPackageName = ps.installerPackageName;
22765            packageAbiOverride = ps.cpuAbiOverrideString;
22766            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22767            seinfo = pkg.applicationInfo.seInfo;
22768            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22769            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22770            freezer = freezePackage(packageName, "movePackageInternal");
22771            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22772        }
22773
22774        final Bundle extras = new Bundle();
22775        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22776        extras.putString(Intent.EXTRA_TITLE, label);
22777        mMoveCallbacks.notifyCreated(moveId, extras);
22778
22779        int installFlags;
22780        final boolean moveCompleteApp;
22781        final File measurePath;
22782
22783        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22784            installFlags = INSTALL_INTERNAL;
22785            moveCompleteApp = !currentAsec;
22786            measurePath = Environment.getDataAppDirectory(volumeUuid);
22787        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22788            installFlags = INSTALL_EXTERNAL;
22789            moveCompleteApp = false;
22790            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22791        } else {
22792            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22793            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22794                    || !volume.isMountedWritable()) {
22795                freezer.close();
22796                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22797                        "Move location not mounted private volume");
22798            }
22799
22800            Preconditions.checkState(!currentAsec);
22801
22802            installFlags = INSTALL_INTERNAL;
22803            moveCompleteApp = true;
22804            measurePath = Environment.getDataAppDirectory(volumeUuid);
22805        }
22806
22807        // If we're moving app data around, we need all the users unlocked
22808        if (moveCompleteApp) {
22809            for (int userId : installedUserIds) {
22810                if (StorageManager.isFileEncryptedNativeOrEmulated()
22811                        && !StorageManager.isUserKeyUnlocked(userId)) {
22812                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22813                            "User " + userId + " must be unlocked");
22814                }
22815            }
22816        }
22817
22818        final PackageStats stats = new PackageStats(null, -1);
22819        synchronized (mInstaller) {
22820            for (int userId : installedUserIds) {
22821                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22822                    freezer.close();
22823                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22824                            "Failed to measure package size");
22825                }
22826            }
22827        }
22828
22829        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22830                + stats.dataSize);
22831
22832        final long startFreeBytes = measurePath.getUsableSpace();
22833        final long sizeBytes;
22834        if (moveCompleteApp) {
22835            sizeBytes = stats.codeSize + stats.dataSize;
22836        } else {
22837            sizeBytes = stats.codeSize;
22838        }
22839
22840        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22841            freezer.close();
22842            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22843                    "Not enough free space to move");
22844        }
22845
22846        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22847
22848        final CountDownLatch installedLatch = new CountDownLatch(1);
22849        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22850            @Override
22851            public void onUserActionRequired(Intent intent) throws RemoteException {
22852                throw new IllegalStateException();
22853            }
22854
22855            @Override
22856            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22857                    Bundle extras) throws RemoteException {
22858                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22859                        + PackageManager.installStatusToString(returnCode, msg));
22860
22861                installedLatch.countDown();
22862                freezer.close();
22863
22864                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22865                switch (status) {
22866                    case PackageInstaller.STATUS_SUCCESS:
22867                        mMoveCallbacks.notifyStatusChanged(moveId,
22868                                PackageManager.MOVE_SUCCEEDED);
22869                        break;
22870                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22871                        mMoveCallbacks.notifyStatusChanged(moveId,
22872                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22873                        break;
22874                    default:
22875                        mMoveCallbacks.notifyStatusChanged(moveId,
22876                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22877                        break;
22878                }
22879            }
22880        };
22881
22882        final MoveInfo move;
22883        if (moveCompleteApp) {
22884            // Kick off a thread to report progress estimates
22885            new Thread() {
22886                @Override
22887                public void run() {
22888                    while (true) {
22889                        try {
22890                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22891                                break;
22892                            }
22893                        } catch (InterruptedException ignored) {
22894                        }
22895
22896                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22897                        final int progress = 10 + (int) MathUtils.constrain(
22898                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22899                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22900                    }
22901                }
22902            }.start();
22903
22904            final String dataAppName = codeFile.getName();
22905            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22906                    dataAppName, appId, seinfo, targetSdkVersion);
22907        } else {
22908            move = null;
22909        }
22910
22911        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22912
22913        final Message msg = mHandler.obtainMessage(INIT_COPY);
22914        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22915        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22916                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22917                packageAbiOverride, null /*grantedPermissions*/,
22918                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22919        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22920        msg.obj = params;
22921
22922        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22923                System.identityHashCode(msg.obj));
22924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22925                System.identityHashCode(msg.obj));
22926
22927        mHandler.sendMessage(msg);
22928    }
22929
22930    @Override
22931    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22933
22934        final int realMoveId = mNextMoveId.getAndIncrement();
22935        final Bundle extras = new Bundle();
22936        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22937        mMoveCallbacks.notifyCreated(realMoveId, extras);
22938
22939        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22940            @Override
22941            public void onCreated(int moveId, Bundle extras) {
22942                // Ignored
22943            }
22944
22945            @Override
22946            public void onStatusChanged(int moveId, int status, long estMillis) {
22947                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22948            }
22949        };
22950
22951        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22952        storage.setPrimaryStorageUuid(volumeUuid, callback);
22953        return realMoveId;
22954    }
22955
22956    @Override
22957    public int getMoveStatus(int moveId) {
22958        mContext.enforceCallingOrSelfPermission(
22959                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22960        return mMoveCallbacks.mLastStatus.get(moveId);
22961    }
22962
22963    @Override
22964    public void registerMoveCallback(IPackageMoveObserver callback) {
22965        mContext.enforceCallingOrSelfPermission(
22966                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22967        mMoveCallbacks.register(callback);
22968    }
22969
22970    @Override
22971    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22972        mContext.enforceCallingOrSelfPermission(
22973                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22974        mMoveCallbacks.unregister(callback);
22975    }
22976
22977    @Override
22978    public boolean setInstallLocation(int loc) {
22979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22980                null);
22981        if (getInstallLocation() == loc) {
22982            return true;
22983        }
22984        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22985                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22986            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22987                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22988            return true;
22989        }
22990        return false;
22991   }
22992
22993    @Override
22994    public int getInstallLocation() {
22995        // allow instant app access
22996        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22997                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22998                PackageHelper.APP_INSTALL_AUTO);
22999    }
23000
23001    /** Called by UserManagerService */
23002    void cleanUpUser(UserManagerService userManager, int userHandle) {
23003        synchronized (mPackages) {
23004            mDirtyUsers.remove(userHandle);
23005            mUserNeedsBadging.delete(userHandle);
23006            mSettings.removeUserLPw(userHandle);
23007            mPendingBroadcasts.remove(userHandle);
23008            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23009            removeUnusedPackagesLPw(userManager, userHandle);
23010        }
23011    }
23012
23013    /**
23014     * We're removing userHandle and would like to remove any downloaded packages
23015     * that are no longer in use by any other user.
23016     * @param userHandle the user being removed
23017     */
23018    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23019        final boolean DEBUG_CLEAN_APKS = false;
23020        int [] users = userManager.getUserIds();
23021        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23022        while (psit.hasNext()) {
23023            PackageSetting ps = psit.next();
23024            if (ps.pkg == null) {
23025                continue;
23026            }
23027            final String packageName = ps.pkg.packageName;
23028            // Skip over if system app
23029            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23030                continue;
23031            }
23032            if (DEBUG_CLEAN_APKS) {
23033                Slog.i(TAG, "Checking package " + packageName);
23034            }
23035            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23036            if (keep) {
23037                if (DEBUG_CLEAN_APKS) {
23038                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23039                }
23040            } else {
23041                for (int i = 0; i < users.length; i++) {
23042                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23043                        keep = true;
23044                        if (DEBUG_CLEAN_APKS) {
23045                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23046                                    + users[i]);
23047                        }
23048                        break;
23049                    }
23050                }
23051            }
23052            if (!keep) {
23053                if (DEBUG_CLEAN_APKS) {
23054                    Slog.i(TAG, "  Removing package " + packageName);
23055                }
23056                mHandler.post(new Runnable() {
23057                    public void run() {
23058                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23059                                userHandle, 0);
23060                    } //end run
23061                });
23062            }
23063        }
23064    }
23065
23066    /** Called by UserManagerService */
23067    void createNewUser(int userId, String[] disallowedPackages) {
23068        synchronized (mInstallLock) {
23069            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23070        }
23071        synchronized (mPackages) {
23072            scheduleWritePackageRestrictionsLocked(userId);
23073            scheduleWritePackageListLocked(userId);
23074            applyFactoryDefaultBrowserLPw(userId);
23075            primeDomainVerificationsLPw(userId);
23076        }
23077    }
23078
23079    void onNewUserCreated(final int userId) {
23080        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23081        synchronized(mPackages) {
23082            // If permission review for legacy apps is required, we represent
23083            // dagerous permissions for such apps as always granted runtime
23084            // permissions to keep per user flag state whether review is needed.
23085            // Hence, if a new user is added we have to propagate dangerous
23086            // permission grants for these legacy apps.
23087            if (mSettings.mPermissions.mPermissionReviewRequired) {
23088// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23089                mPermissionManager.updateAllPermissions(
23090                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23091                        mPermissionCallback);
23092            }
23093        }
23094    }
23095
23096    @Override
23097    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23098        mContext.enforceCallingOrSelfPermission(
23099                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23100                "Only package verification agents can read the verifier device identity");
23101
23102        synchronized (mPackages) {
23103            return mSettings.getVerifierDeviceIdentityLPw();
23104        }
23105    }
23106
23107    @Override
23108    public void setPermissionEnforced(String permission, boolean enforced) {
23109        // TODO: Now that we no longer change GID for storage, this should to away.
23110        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23111                "setPermissionEnforced");
23112        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23113            synchronized (mPackages) {
23114                if (mSettings.mReadExternalStorageEnforced == null
23115                        || mSettings.mReadExternalStorageEnforced != enforced) {
23116                    mSettings.mReadExternalStorageEnforced =
23117                            enforced ? Boolean.TRUE : Boolean.FALSE;
23118                    mSettings.writeLPr();
23119                }
23120            }
23121            // kill any non-foreground processes so we restart them and
23122            // grant/revoke the GID.
23123            final IActivityManager am = ActivityManager.getService();
23124            if (am != null) {
23125                final long token = Binder.clearCallingIdentity();
23126                try {
23127                    am.killProcessesBelowForeground("setPermissionEnforcement");
23128                } catch (RemoteException e) {
23129                } finally {
23130                    Binder.restoreCallingIdentity(token);
23131                }
23132            }
23133        } else {
23134            throw new IllegalArgumentException("No selective enforcement for " + permission);
23135        }
23136    }
23137
23138    @Override
23139    @Deprecated
23140    public boolean isPermissionEnforced(String permission) {
23141        // allow instant applications
23142        return true;
23143    }
23144
23145    @Override
23146    public boolean isStorageLow() {
23147        // allow instant applications
23148        final long token = Binder.clearCallingIdentity();
23149        try {
23150            final DeviceStorageMonitorInternal
23151                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23152            if (dsm != null) {
23153                return dsm.isMemoryLow();
23154            } else {
23155                return false;
23156            }
23157        } finally {
23158            Binder.restoreCallingIdentity(token);
23159        }
23160    }
23161
23162    @Override
23163    public IPackageInstaller getPackageInstaller() {
23164        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23165            return null;
23166        }
23167        return mInstallerService;
23168    }
23169
23170    @Override
23171    public IArtManager getArtManager() {
23172        return mArtManagerService;
23173    }
23174
23175    private boolean userNeedsBadging(int userId) {
23176        int index = mUserNeedsBadging.indexOfKey(userId);
23177        if (index < 0) {
23178            final UserInfo userInfo;
23179            final long token = Binder.clearCallingIdentity();
23180            try {
23181                userInfo = sUserManager.getUserInfo(userId);
23182            } finally {
23183                Binder.restoreCallingIdentity(token);
23184            }
23185            final boolean b;
23186            if (userInfo != null && userInfo.isManagedProfile()) {
23187                b = true;
23188            } else {
23189                b = false;
23190            }
23191            mUserNeedsBadging.put(userId, b);
23192            return b;
23193        }
23194        return mUserNeedsBadging.valueAt(index);
23195    }
23196
23197    @Override
23198    public KeySet getKeySetByAlias(String packageName, String alias) {
23199        if (packageName == null || alias == null) {
23200            return null;
23201        }
23202        synchronized(mPackages) {
23203            final PackageParser.Package pkg = mPackages.get(packageName);
23204            if (pkg == null) {
23205                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23206                throw new IllegalArgumentException("Unknown package: " + packageName);
23207            }
23208            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23209            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23210                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23211                throw new IllegalArgumentException("Unknown package: " + packageName);
23212            }
23213            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23214            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23215        }
23216    }
23217
23218    @Override
23219    public KeySet getSigningKeySet(String packageName) {
23220        if (packageName == null) {
23221            return null;
23222        }
23223        synchronized(mPackages) {
23224            final int callingUid = Binder.getCallingUid();
23225            final int callingUserId = UserHandle.getUserId(callingUid);
23226            final PackageParser.Package pkg = mPackages.get(packageName);
23227            if (pkg == null) {
23228                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23229                throw new IllegalArgumentException("Unknown package: " + packageName);
23230            }
23231            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23232            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23233                // filter and pretend the package doesn't exist
23234                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23235                        + ", uid:" + callingUid);
23236                throw new IllegalArgumentException("Unknown package: " + packageName);
23237            }
23238            if (pkg.applicationInfo.uid != callingUid
23239                    && Process.SYSTEM_UID != callingUid) {
23240                throw new SecurityException("May not access signing KeySet of other apps.");
23241            }
23242            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23243            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23244        }
23245    }
23246
23247    @Override
23248    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23249        final int callingUid = Binder.getCallingUid();
23250        if (getInstantAppPackageName(callingUid) != null) {
23251            return false;
23252        }
23253        if (packageName == null || ks == null) {
23254            return false;
23255        }
23256        synchronized(mPackages) {
23257            final PackageParser.Package pkg = mPackages.get(packageName);
23258            if (pkg == null
23259                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23260                            UserHandle.getUserId(callingUid))) {
23261                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23262                throw new IllegalArgumentException("Unknown package: " + packageName);
23263            }
23264            IBinder ksh = ks.getToken();
23265            if (ksh instanceof KeySetHandle) {
23266                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23267                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23268            }
23269            return false;
23270        }
23271    }
23272
23273    @Override
23274    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23275        final int callingUid = Binder.getCallingUid();
23276        if (getInstantAppPackageName(callingUid) != null) {
23277            return false;
23278        }
23279        if (packageName == null || ks == null) {
23280            return false;
23281        }
23282        synchronized(mPackages) {
23283            final PackageParser.Package pkg = mPackages.get(packageName);
23284            if (pkg == null
23285                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23286                            UserHandle.getUserId(callingUid))) {
23287                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23288                throw new IllegalArgumentException("Unknown package: " + packageName);
23289            }
23290            IBinder ksh = ks.getToken();
23291            if (ksh instanceof KeySetHandle) {
23292                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23293                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23294            }
23295            return false;
23296        }
23297    }
23298
23299    private void deletePackageIfUnusedLPr(final String packageName) {
23300        PackageSetting ps = mSettings.mPackages.get(packageName);
23301        if (ps == null) {
23302            return;
23303        }
23304        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23305            // TODO Implement atomic delete if package is unused
23306            // It is currently possible that the package will be deleted even if it is installed
23307            // after this method returns.
23308            mHandler.post(new Runnable() {
23309                public void run() {
23310                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23311                            0, PackageManager.DELETE_ALL_USERS);
23312                }
23313            });
23314        }
23315    }
23316
23317    /**
23318     * Check and throw if the given before/after packages would be considered a
23319     * downgrade.
23320     */
23321    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23322            throws PackageManagerException {
23323        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23324            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23325                    "Update version code " + after.versionCode + " is older than current "
23326                    + before.getLongVersionCode());
23327        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23328            if (after.baseRevisionCode < before.baseRevisionCode) {
23329                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23330                        "Update base revision code " + after.baseRevisionCode
23331                        + " is older than current " + before.baseRevisionCode);
23332            }
23333
23334            if (!ArrayUtils.isEmpty(after.splitNames)) {
23335                for (int i = 0; i < after.splitNames.length; i++) {
23336                    final String splitName = after.splitNames[i];
23337                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23338                    if (j != -1) {
23339                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23340                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23341                                    "Update split " + splitName + " revision code "
23342                                    + after.splitRevisionCodes[i] + " is older than current "
23343                                    + before.splitRevisionCodes[j]);
23344                        }
23345                    }
23346                }
23347            }
23348        }
23349    }
23350
23351    private static class MoveCallbacks extends Handler {
23352        private static final int MSG_CREATED = 1;
23353        private static final int MSG_STATUS_CHANGED = 2;
23354
23355        private final RemoteCallbackList<IPackageMoveObserver>
23356                mCallbacks = new RemoteCallbackList<>();
23357
23358        private final SparseIntArray mLastStatus = new SparseIntArray();
23359
23360        public MoveCallbacks(Looper looper) {
23361            super(looper);
23362        }
23363
23364        public void register(IPackageMoveObserver callback) {
23365            mCallbacks.register(callback);
23366        }
23367
23368        public void unregister(IPackageMoveObserver callback) {
23369            mCallbacks.unregister(callback);
23370        }
23371
23372        @Override
23373        public void handleMessage(Message msg) {
23374            final SomeArgs args = (SomeArgs) msg.obj;
23375            final int n = mCallbacks.beginBroadcast();
23376            for (int i = 0; i < n; i++) {
23377                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23378                try {
23379                    invokeCallback(callback, msg.what, args);
23380                } catch (RemoteException ignored) {
23381                }
23382            }
23383            mCallbacks.finishBroadcast();
23384            args.recycle();
23385        }
23386
23387        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23388                throws RemoteException {
23389            switch (what) {
23390                case MSG_CREATED: {
23391                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23392                    break;
23393                }
23394                case MSG_STATUS_CHANGED: {
23395                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23396                    break;
23397                }
23398            }
23399        }
23400
23401        private void notifyCreated(int moveId, Bundle extras) {
23402            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23403
23404            final SomeArgs args = SomeArgs.obtain();
23405            args.argi1 = moveId;
23406            args.arg2 = extras;
23407            obtainMessage(MSG_CREATED, args).sendToTarget();
23408        }
23409
23410        private void notifyStatusChanged(int moveId, int status) {
23411            notifyStatusChanged(moveId, status, -1);
23412        }
23413
23414        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23415            Slog.v(TAG, "Move " + moveId + " status " + status);
23416
23417            final SomeArgs args = SomeArgs.obtain();
23418            args.argi1 = moveId;
23419            args.argi2 = status;
23420            args.arg3 = estMillis;
23421            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23422
23423            synchronized (mLastStatus) {
23424                mLastStatus.put(moveId, status);
23425            }
23426        }
23427    }
23428
23429    private final static class OnPermissionChangeListeners extends Handler {
23430        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23431
23432        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23433                new RemoteCallbackList<>();
23434
23435        public OnPermissionChangeListeners(Looper looper) {
23436            super(looper);
23437        }
23438
23439        @Override
23440        public void handleMessage(Message msg) {
23441            switch (msg.what) {
23442                case MSG_ON_PERMISSIONS_CHANGED: {
23443                    final int uid = msg.arg1;
23444                    handleOnPermissionsChanged(uid);
23445                } break;
23446            }
23447        }
23448
23449        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23450            mPermissionListeners.register(listener);
23451
23452        }
23453
23454        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23455            mPermissionListeners.unregister(listener);
23456        }
23457
23458        public void onPermissionsChanged(int uid) {
23459            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23460                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23461            }
23462        }
23463
23464        private void handleOnPermissionsChanged(int uid) {
23465            final int count = mPermissionListeners.beginBroadcast();
23466            try {
23467                for (int i = 0; i < count; i++) {
23468                    IOnPermissionsChangeListener callback = mPermissionListeners
23469                            .getBroadcastItem(i);
23470                    try {
23471                        callback.onPermissionsChanged(uid);
23472                    } catch (RemoteException e) {
23473                        Log.e(TAG, "Permission listener is dead", e);
23474                    }
23475                }
23476            } finally {
23477                mPermissionListeners.finishBroadcast();
23478            }
23479        }
23480    }
23481
23482    private class PackageManagerNative extends IPackageManagerNative.Stub {
23483        @Override
23484        public String[] getNamesForUids(int[] uids) throws RemoteException {
23485            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23486            // massage results so they can be parsed by the native binder
23487            for (int i = results.length - 1; i >= 0; --i) {
23488                if (results[i] == null) {
23489                    results[i] = "";
23490                }
23491            }
23492            return results;
23493        }
23494
23495        // NB: this differentiates between preloads and sideloads
23496        @Override
23497        public String getInstallerForPackage(String packageName) throws RemoteException {
23498            final String installerName = getInstallerPackageName(packageName);
23499            if (!TextUtils.isEmpty(installerName)) {
23500                return installerName;
23501            }
23502            // differentiate between preload and sideload
23503            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23504            ApplicationInfo appInfo = getApplicationInfo(packageName,
23505                                    /*flags*/ 0,
23506                                    /*userId*/ callingUser);
23507            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23508                return "preload";
23509            }
23510            return "";
23511        }
23512
23513        @Override
23514        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23515            try {
23516                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23517                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23518                if (pInfo != null) {
23519                    return pInfo.getLongVersionCode();
23520                }
23521            } catch (Exception e) {
23522            }
23523            return 0;
23524        }
23525    }
23526
23527    private class PackageManagerInternalImpl extends PackageManagerInternal {
23528        @Override
23529        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23530                int flagValues, int userId) {
23531            PackageManagerService.this.updatePermissionFlags(
23532                    permName, packageName, flagMask, flagValues, userId);
23533        }
23534
23535        @Override
23536        public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
23537            SigningDetails sd = getSigningDetails(packageName);
23538            if (sd == null) {
23539                return false;
23540            }
23541            return sd.hasSha256Certificate(restoringFromSigHash,
23542                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23543        }
23544
23545        @Override
23546        public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
23547            SigningDetails sd = getSigningDetails(packageName);
23548            if (sd == null) {
23549                return false;
23550            }
23551            return sd.hasCertificate(restoringFromSig,
23552                    SigningDetails.CertCapabilities.INSTALLED_DATA);
23553        }
23554
23555        private SigningDetails getSigningDetails(@NonNull String packageName) {
23556            synchronized (mPackages) {
23557                PackageParser.Package p = mPackages.get(packageName);
23558                if (p == null) {
23559                    return null;
23560                }
23561                return p.mSigningDetails;
23562            }
23563        }
23564
23565        @Override
23566        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23567            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23568        }
23569
23570        @Override
23571        public boolean isInstantApp(String packageName, int userId) {
23572            return PackageManagerService.this.isInstantApp(packageName, userId);
23573        }
23574
23575        @Override
23576        public String getInstantAppPackageName(int uid) {
23577            return PackageManagerService.this.getInstantAppPackageName(uid);
23578        }
23579
23580        @Override
23581        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23582            synchronized (mPackages) {
23583                return PackageManagerService.this.filterAppAccessLPr(
23584                        (PackageSetting) pkg.mExtras, callingUid, userId);
23585            }
23586        }
23587
23588        @Override
23589        public PackageParser.Package getPackage(String packageName) {
23590            synchronized (mPackages) {
23591                packageName = resolveInternalPackageNameLPr(
23592                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23593                return mPackages.get(packageName);
23594            }
23595        }
23596
23597        @Override
23598        public PackageList getPackageList(PackageListObserver observer) {
23599            synchronized (mPackages) {
23600                final int N = mPackages.size();
23601                final ArrayList<String> list = new ArrayList<>(N);
23602                for (int i = 0; i < N; i++) {
23603                    list.add(mPackages.keyAt(i));
23604                }
23605                final PackageList packageList = new PackageList(list, observer);
23606                if (observer != null) {
23607                    mPackageListObservers.add(packageList);
23608                }
23609                return packageList;
23610            }
23611        }
23612
23613        @Override
23614        public void removePackageListObserver(PackageListObserver observer) {
23615            synchronized (mPackages) {
23616                mPackageListObservers.remove(observer);
23617            }
23618        }
23619
23620        @Override
23621        public PackageParser.Package getDisabledPackage(String packageName) {
23622            synchronized (mPackages) {
23623                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23624                return (ps != null) ? ps.pkg : null;
23625            }
23626        }
23627
23628        @Override
23629        public String getKnownPackageName(int knownPackage, int userId) {
23630            switch(knownPackage) {
23631                case PackageManagerInternal.PACKAGE_BROWSER:
23632                    return getDefaultBrowserPackageName(userId);
23633                case PackageManagerInternal.PACKAGE_INSTALLER:
23634                    return mRequiredInstallerPackage;
23635                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23636                    return mSetupWizardPackage;
23637                case PackageManagerInternal.PACKAGE_SYSTEM:
23638                    return "android";
23639                case PackageManagerInternal.PACKAGE_VERIFIER:
23640                    return mRequiredVerifierPackage;
23641                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23642                    return mSystemTextClassifierPackage;
23643            }
23644            return null;
23645        }
23646
23647        @Override
23648        public boolean isResolveActivityComponent(ComponentInfo component) {
23649            return mResolveActivity.packageName.equals(component.packageName)
23650                    && mResolveActivity.name.equals(component.name);
23651        }
23652
23653        @Override
23654        public void setLocationPackagesProvider(PackagesProvider provider) {
23655            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23656        }
23657
23658        @Override
23659        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23660            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23661        }
23662
23663        @Override
23664        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23665            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23666        }
23667
23668        @Override
23669        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23670            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23671        }
23672
23673        @Override
23674        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23675            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23676        }
23677
23678        @Override
23679        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23680            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23681        }
23682
23683        @Override
23684        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23685            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23686        }
23687
23688        @Override
23689        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23690            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23691        }
23692
23693        @Override
23694        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23695            synchronized (mPackages) {
23696                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23697            }
23698            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23699        }
23700
23701        @Override
23702        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23703            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23704                    packageName, userId);
23705        }
23706
23707        @Override
23708        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23709            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23710                    packageName, userId);
23711        }
23712
23713        @Override
23714        public void setKeepUninstalledPackages(final List<String> packageList) {
23715            Preconditions.checkNotNull(packageList);
23716            List<String> removedFromList = null;
23717            synchronized (mPackages) {
23718                if (mKeepUninstalledPackages != null) {
23719                    final int packagesCount = mKeepUninstalledPackages.size();
23720                    for (int i = 0; i < packagesCount; i++) {
23721                        String oldPackage = mKeepUninstalledPackages.get(i);
23722                        if (packageList != null && packageList.contains(oldPackage)) {
23723                            continue;
23724                        }
23725                        if (removedFromList == null) {
23726                            removedFromList = new ArrayList<>();
23727                        }
23728                        removedFromList.add(oldPackage);
23729                    }
23730                }
23731                mKeepUninstalledPackages = new ArrayList<>(packageList);
23732                if (removedFromList != null) {
23733                    final int removedCount = removedFromList.size();
23734                    for (int i = 0; i < removedCount; i++) {
23735                        deletePackageIfUnusedLPr(removedFromList.get(i));
23736                    }
23737                }
23738            }
23739        }
23740
23741        @Override
23742        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23743            synchronized (mPackages) {
23744                return mPermissionManager.isPermissionsReviewRequired(
23745                        mPackages.get(packageName), userId);
23746            }
23747        }
23748
23749        @Override
23750        public PackageInfo getPackageInfo(
23751                String packageName, int flags, int filterCallingUid, int userId) {
23752            return PackageManagerService.this
23753                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23754                            flags, filterCallingUid, userId);
23755        }
23756
23757        @Override
23758        public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
23759            synchronized (mPackages) {
23760                final PackageSetting ps = mSettings.mPackages.get(packageName);
23761                PersistableBundle launcherExtras = null;
23762                if (ps != null) {
23763                    launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
23764                }
23765                return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
23766            }
23767        }
23768
23769        @Override
23770        public int getPackageUid(String packageName, int flags, int userId) {
23771            return PackageManagerService.this
23772                    .getPackageUid(packageName, flags, userId);
23773        }
23774
23775        @Override
23776        public ApplicationInfo getApplicationInfo(
23777                String packageName, int flags, int filterCallingUid, int userId) {
23778            return PackageManagerService.this
23779                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23780        }
23781
23782        @Override
23783        public ActivityInfo getActivityInfo(
23784                ComponentName component, int flags, int filterCallingUid, int userId) {
23785            return PackageManagerService.this
23786                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23787        }
23788
23789        @Override
23790        public List<ResolveInfo> queryIntentActivities(
23791                Intent intent, int flags, int filterCallingUid, int userId) {
23792            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23793            return PackageManagerService.this
23794                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23795                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23796        }
23797
23798        @Override
23799        public List<ResolveInfo> queryIntentServices(
23800                Intent intent, int flags, int callingUid, int userId) {
23801            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23802            return PackageManagerService.this
23803                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23804                            false);
23805        }
23806
23807        @Override
23808        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23809                int userId) {
23810            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23811        }
23812
23813        @Override
23814        public ComponentName getDefaultHomeActivity(int userId) {
23815            return PackageManagerService.this.getDefaultHomeActivity(userId);
23816        }
23817
23818        @Override
23819        public void setDeviceAndProfileOwnerPackages(
23820                int deviceOwnerUserId, String deviceOwnerPackage,
23821                SparseArray<String> profileOwnerPackages) {
23822            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23823                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23824        }
23825
23826        @Override
23827        public boolean isPackageDataProtected(int userId, String packageName) {
23828            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23829        }
23830
23831        @Override
23832        public boolean isPackageEphemeral(int userId, String packageName) {
23833            synchronized (mPackages) {
23834                final PackageSetting ps = mSettings.mPackages.get(packageName);
23835                return ps != null ? ps.getInstantApp(userId) : false;
23836            }
23837        }
23838
23839        @Override
23840        public boolean wasPackageEverLaunched(String packageName, int userId) {
23841            synchronized (mPackages) {
23842                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23843            }
23844        }
23845
23846        @Override
23847        public void grantRuntimePermission(String packageName, String permName, int userId,
23848                boolean overridePolicy) {
23849            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23850                    permName, packageName, overridePolicy, getCallingUid(), userId,
23851                    mPermissionCallback);
23852        }
23853
23854        @Override
23855        public void revokeRuntimePermission(String packageName, String permName, int userId,
23856                boolean overridePolicy) {
23857            mPermissionManager.revokeRuntimePermission(
23858                    permName, packageName, overridePolicy, getCallingUid(), userId,
23859                    mPermissionCallback);
23860        }
23861
23862        @Override
23863        public String getNameForUid(int uid) {
23864            return PackageManagerService.this.getNameForUid(uid);
23865        }
23866
23867        @Override
23868        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23869                Intent origIntent, String resolvedType, String callingPackage,
23870                Bundle verificationBundle, int userId) {
23871            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23872                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23873                    userId);
23874        }
23875
23876        @Override
23877        public void grantEphemeralAccess(int userId, Intent intent,
23878                int targetAppId, int ephemeralAppId) {
23879            synchronized (mPackages) {
23880                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23881                        targetAppId, ephemeralAppId);
23882            }
23883        }
23884
23885        @Override
23886        public boolean isInstantAppInstallerComponent(ComponentName component) {
23887            synchronized (mPackages) {
23888                return mInstantAppInstallerActivity != null
23889                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23890            }
23891        }
23892
23893        @Override
23894        public void pruneInstantApps() {
23895            mInstantAppRegistry.pruneInstantApps();
23896        }
23897
23898        @Override
23899        public String getSetupWizardPackageName() {
23900            return mSetupWizardPackage;
23901        }
23902
23903        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23904            if (policy != null) {
23905                mExternalSourcesPolicy = policy;
23906            }
23907        }
23908
23909        @Override
23910        public boolean isPackagePersistent(String packageName) {
23911            synchronized (mPackages) {
23912                PackageParser.Package pkg = mPackages.get(packageName);
23913                return pkg != null
23914                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23915                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23916                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23917                        : false;
23918            }
23919        }
23920
23921        @Override
23922        public boolean isLegacySystemApp(Package pkg) {
23923            synchronized (mPackages) {
23924                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23925                return mPromoteSystemApps
23926                        && ps.isSystem()
23927                        && mExistingSystemPackages.contains(ps.name);
23928            }
23929        }
23930
23931        @Override
23932        public List<PackageInfo> getOverlayPackages(int userId) {
23933            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23934            synchronized (mPackages) {
23935                for (PackageParser.Package p : mPackages.values()) {
23936                    if (p.mOverlayTarget != null) {
23937                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23938                        if (pkg != null) {
23939                            overlayPackages.add(pkg);
23940                        }
23941                    }
23942                }
23943            }
23944            return overlayPackages;
23945        }
23946
23947        @Override
23948        public List<String> getTargetPackageNames(int userId) {
23949            List<String> targetPackages = new ArrayList<>();
23950            synchronized (mPackages) {
23951                for (PackageParser.Package p : mPackages.values()) {
23952                    if (p.mOverlayTarget == null) {
23953                        targetPackages.add(p.packageName);
23954                    }
23955                }
23956            }
23957            return targetPackages;
23958        }
23959
23960        @Override
23961        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23962                @Nullable List<String> overlayPackageNames) {
23963            synchronized (mPackages) {
23964                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23965                    Slog.e(TAG, "failed to find package " + targetPackageName);
23966                    return false;
23967                }
23968                ArrayList<String> overlayPaths = null;
23969                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23970                    final int N = overlayPackageNames.size();
23971                    overlayPaths = new ArrayList<>(N);
23972                    for (int i = 0; i < N; i++) {
23973                        final String packageName = overlayPackageNames.get(i);
23974                        final PackageParser.Package pkg = mPackages.get(packageName);
23975                        if (pkg == null) {
23976                            Slog.e(TAG, "failed to find package " + packageName);
23977                            return false;
23978                        }
23979                        overlayPaths.add(pkg.baseCodePath);
23980                    }
23981                }
23982
23983                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23984                ps.setOverlayPaths(overlayPaths, userId);
23985                return true;
23986            }
23987        }
23988
23989        @Override
23990        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23991                int flags, int userId, boolean resolveForStart) {
23992            return resolveIntentInternal(
23993                    intent, resolvedType, flags, userId, resolveForStart);
23994        }
23995
23996        @Override
23997        public ResolveInfo resolveService(Intent intent, String resolvedType,
23998                int flags, int userId, int callingUid) {
23999            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24000        }
24001
24002        @Override
24003        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24004            return PackageManagerService.this.resolveContentProviderInternal(
24005                    name, flags, userId);
24006        }
24007
24008        @Override
24009        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24010            synchronized (mPackages) {
24011                mIsolatedOwners.put(isolatedUid, ownerUid);
24012            }
24013        }
24014
24015        @Override
24016        public void removeIsolatedUid(int isolatedUid) {
24017            synchronized (mPackages) {
24018                mIsolatedOwners.delete(isolatedUid);
24019            }
24020        }
24021
24022        @Override
24023        public int getUidTargetSdkVersion(int uid) {
24024            synchronized (mPackages) {
24025                return getUidTargetSdkVersionLockedLPr(uid);
24026            }
24027        }
24028
24029        @Override
24030        public int getPackageTargetSdkVersion(String packageName) {
24031            synchronized (mPackages) {
24032                return getPackageTargetSdkVersionLockedLPr(packageName);
24033            }
24034        }
24035
24036        @Override
24037        public boolean canAccessInstantApps(int callingUid, int userId) {
24038            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24039        }
24040
24041        @Override
24042        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24043            synchronized (mPackages) {
24044                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24045                return !PackageManagerService.this.filterAppAccessLPr(
24046                        ps, callingUid, component, TYPE_UNKNOWN, userId);
24047            }
24048        }
24049
24050        @Override
24051        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24052            synchronized (mPackages) {
24053                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24054            }
24055        }
24056
24057        @Override
24058        public void notifyPackageUse(String packageName, int reason) {
24059            synchronized (mPackages) {
24060                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24061            }
24062        }
24063    }
24064
24065    @Override
24066    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24067        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24068        synchronized (mPackages) {
24069            final long identity = Binder.clearCallingIdentity();
24070            try {
24071                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24072                        packageNames, userId);
24073            } finally {
24074                Binder.restoreCallingIdentity(identity);
24075            }
24076        }
24077    }
24078
24079    @Override
24080    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24081        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24082        synchronized (mPackages) {
24083            final long identity = Binder.clearCallingIdentity();
24084            try {
24085                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24086                        packageNames, userId);
24087            } finally {
24088                Binder.restoreCallingIdentity(identity);
24089            }
24090        }
24091    }
24092
24093    @Override
24094    public void grantDefaultPermissionsToEnabledTelephonyDataServices(
24095            String[] packageNames, int userId) {
24096        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
24097        synchronized (mPackages) {
24098            Binder.withCleanCallingIdentity( () -> {
24099                mDefaultPermissionPolicy.
24100                        grantDefaultPermissionsToEnabledTelephonyDataServices(
24101                                packageNames, userId);
24102            });
24103        }
24104    }
24105
24106    @Override
24107    public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24108            String[] packageNames, int userId) {
24109        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
24110        synchronized (mPackages) {
24111            Binder.withCleanCallingIdentity( () -> {
24112                mDefaultPermissionPolicy.
24113                        revokeDefaultPermissionsFromDisabledTelephonyDataServices(
24114                                packageNames, userId);
24115            });
24116        }
24117    }
24118
24119    @Override
24120    public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
24121        enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
24122        synchronized (mPackages) {
24123            final long identity = Binder.clearCallingIdentity();
24124            try {
24125                mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
24126                        packageName, userId);
24127            } finally {
24128                Binder.restoreCallingIdentity(identity);
24129            }
24130        }
24131    }
24132
24133    @Override
24134    public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
24135        enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
24136        synchronized (mPackages) {
24137            final long identity = Binder.clearCallingIdentity();
24138            try {
24139                mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
24140            } finally {
24141                Binder.restoreCallingIdentity(identity);
24142            }
24143        }
24144    }
24145
24146    private static void enforceSystemOrPhoneCaller(String tag) {
24147        int callingUid = Binder.getCallingUid();
24148        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24149            throw new SecurityException(
24150                    "Cannot call " + tag + " from UID " + callingUid);
24151        }
24152    }
24153
24154    boolean isHistoricalPackageUsageAvailable() {
24155        return mPackageUsage.isHistoricalPackageUsageAvailable();
24156    }
24157
24158    /**
24159     * Return a <b>copy</b> of the collection of packages known to the package manager.
24160     * @return A copy of the values of mPackages.
24161     */
24162    Collection<PackageParser.Package> getPackages() {
24163        synchronized (mPackages) {
24164            return new ArrayList<>(mPackages.values());
24165        }
24166    }
24167
24168    /**
24169     * Logs process start information (including base APK hash) to the security log.
24170     * @hide
24171     */
24172    @Override
24173    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24174            String apkFile, int pid) {
24175        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24176            return;
24177        }
24178        if (!SecurityLog.isLoggingEnabled()) {
24179            return;
24180        }
24181        Bundle data = new Bundle();
24182        data.putLong("startTimestamp", System.currentTimeMillis());
24183        data.putString("processName", processName);
24184        data.putInt("uid", uid);
24185        data.putString("seinfo", seinfo);
24186        data.putString("apkFile", apkFile);
24187        data.putInt("pid", pid);
24188        Message msg = mProcessLoggingHandler.obtainMessage(
24189                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24190        msg.setData(data);
24191        mProcessLoggingHandler.sendMessage(msg);
24192    }
24193
24194    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24195        return mCompilerStats.getPackageStats(pkgName);
24196    }
24197
24198    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24199        return getOrCreateCompilerPackageStats(pkg.packageName);
24200    }
24201
24202    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24203        return mCompilerStats.getOrCreatePackageStats(pkgName);
24204    }
24205
24206    public void deleteCompilerPackageStats(String pkgName) {
24207        mCompilerStats.deletePackageStats(pkgName);
24208    }
24209
24210    @Override
24211    public int getInstallReason(String packageName, int userId) {
24212        final int callingUid = Binder.getCallingUid();
24213        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24214                true /* requireFullPermission */, false /* checkShell */,
24215                "get install reason");
24216        synchronized (mPackages) {
24217            final PackageSetting ps = mSettings.mPackages.get(packageName);
24218            if (filterAppAccessLPr(ps, callingUid, userId)) {
24219                return PackageManager.INSTALL_REASON_UNKNOWN;
24220            }
24221            if (ps != null) {
24222                return ps.getInstallReason(userId);
24223            }
24224        }
24225        return PackageManager.INSTALL_REASON_UNKNOWN;
24226    }
24227
24228    @Override
24229    public boolean canRequestPackageInstalls(String packageName, int userId) {
24230        return canRequestPackageInstallsInternal(packageName, 0, userId,
24231                true /* throwIfPermNotDeclared*/);
24232    }
24233
24234    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24235            boolean throwIfPermNotDeclared) {
24236        int callingUid = Binder.getCallingUid();
24237        int uid = getPackageUid(packageName, 0, userId);
24238        if (callingUid != uid && callingUid != Process.ROOT_UID
24239                && callingUid != Process.SYSTEM_UID) {
24240            throw new SecurityException(
24241                    "Caller uid " + callingUid + " does not own package " + packageName);
24242        }
24243        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24244        if (info == null) {
24245            return false;
24246        }
24247        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24248            return false;
24249        }
24250        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24251        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24252        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24253            if (throwIfPermNotDeclared) {
24254                throw new SecurityException("Need to declare " + appOpPermission
24255                        + " to call this api");
24256            } else {
24257                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24258                return false;
24259            }
24260        }
24261        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24262            return false;
24263        }
24264        if (mExternalSourcesPolicy != null) {
24265            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24266            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24267                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24268            }
24269        }
24270        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24271    }
24272
24273    @Override
24274    public ComponentName getInstantAppResolverSettingsComponent() {
24275        return mInstantAppResolverSettingsComponent;
24276    }
24277
24278    @Override
24279    public ComponentName getInstantAppInstallerComponent() {
24280        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24281            return null;
24282        }
24283        return mInstantAppInstallerActivity == null
24284                ? null : mInstantAppInstallerActivity.getComponentName();
24285    }
24286
24287    @Override
24288    public String getInstantAppAndroidId(String packageName, int userId) {
24289        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24290                "getInstantAppAndroidId");
24291        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24292                true /* requireFullPermission */, false /* checkShell */,
24293                "getInstantAppAndroidId");
24294        // Make sure the target is an Instant App.
24295        if (!isInstantApp(packageName, userId)) {
24296            return null;
24297        }
24298        synchronized (mPackages) {
24299            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24300        }
24301    }
24302
24303    boolean canHaveOatDir(String packageName) {
24304        synchronized (mPackages) {
24305            PackageParser.Package p = mPackages.get(packageName);
24306            if (p == null) {
24307                return false;
24308            }
24309            return p.canHaveOatDir();
24310        }
24311    }
24312
24313    private String getOatDir(PackageParser.Package pkg) {
24314        if (!pkg.canHaveOatDir()) {
24315            return null;
24316        }
24317        File codePath = new File(pkg.codePath);
24318        if (codePath.isDirectory()) {
24319            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24320        }
24321        return null;
24322    }
24323
24324    void deleteOatArtifactsOfPackage(String packageName) {
24325        final String[] instructionSets;
24326        final List<String> codePaths;
24327        final String oatDir;
24328        final PackageParser.Package pkg;
24329        synchronized (mPackages) {
24330            pkg = mPackages.get(packageName);
24331        }
24332        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24333        codePaths = pkg.getAllCodePaths();
24334        oatDir = getOatDir(pkg);
24335
24336        for (String codePath : codePaths) {
24337            for (String isa : instructionSets) {
24338                try {
24339                    mInstaller.deleteOdex(codePath, isa, oatDir);
24340                } catch (InstallerException e) {
24341                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24342                }
24343            }
24344        }
24345    }
24346
24347    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24348        Set<String> unusedPackages = new HashSet<>();
24349        long currentTimeInMillis = System.currentTimeMillis();
24350        synchronized (mPackages) {
24351            for (PackageParser.Package pkg : mPackages.values()) {
24352                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24353                if (ps == null) {
24354                    continue;
24355                }
24356                PackageDexUsage.PackageUseInfo packageUseInfo =
24357                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24358                if (PackageManagerServiceUtils
24359                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24360                                downgradeTimeThresholdMillis, packageUseInfo,
24361                                pkg.getLatestPackageUseTimeInMills(),
24362                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24363                    unusedPackages.add(pkg.packageName);
24364                }
24365            }
24366        }
24367        return unusedPackages;
24368    }
24369
24370    @Override
24371    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24372            int userId) {
24373        final int callingUid = Binder.getCallingUid();
24374        final int callingAppId = UserHandle.getAppId(callingUid);
24375
24376        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24377                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24378
24379        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24380                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24381            throw new SecurityException("Caller must have the "
24382                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24383        }
24384
24385        synchronized(mPackages) {
24386            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24387            scheduleWritePackageRestrictionsLocked(userId);
24388        }
24389    }
24390
24391    @Nullable
24392    @Override
24393    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24394        final int callingUid = Binder.getCallingUid();
24395        final int callingAppId = UserHandle.getAppId(callingUid);
24396
24397        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24398                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24399
24400        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24401                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24402            throw new SecurityException("Caller must have the "
24403                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24404        }
24405
24406        synchronized(mPackages) {
24407            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24408        }
24409    }
24410
24411    @Override
24412    public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
24413        final int callingUid = Binder.getCallingUid();
24414        final int callingAppId = UserHandle.getAppId(callingUid);
24415
24416        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24417                false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
24418
24419        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
24420                && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
24421            throw new SecurityException("Caller must have the "
24422                    + MANAGE_DEVICE_ADMINS + " permission.");
24423        }
24424
24425        return mProtectedPackages.isPackageStateProtected(userId, packageName);
24426    }
24427}
24428
24429interface PackageSender {
24430    /**
24431     * @param userIds User IDs where the action occurred on a full application
24432     * @param instantUserIds User IDs where the action occurred on an instant application
24433     */
24434    void sendPackageBroadcast(final String action, final String pkg,
24435        final Bundle extras, final int flags, final String targetPkg,
24436        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24437    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24438        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24439    void notifyPackageAdded(String packageName);
24440    void notifyPackageRemoved(String packageName);
24441}
24442